2015-01-13 3 views
0

컬렉션에 키를 추가 할 때 이상한 문제가 있습니다. 런타임 오류 13 : 형식 불일치VBA에서 컬렉션에 키 추가

모듈 코드 :

'comment 
Option Explicit 
'comment 
Sub testChildren() 
    'This is in Normal module 
    Dim mRoot As cMyClass, mc As cMyClass 
    Set mRoot = New cMyClass 
    With mRoot 
     'add collections 
     .Init 100, "john" 

     Set mc = New cMyClass 
     ' Here I add the key that gives the run-time error 13 
     .Children.Add mc.Init(200, "janet"), mc.Key 

     Set mc = New cMyClass 
     ' This one also generates run-time error 13 in case the previous adding is disabled 
     .Children.Add mc.Init(201, "john"), mc.Key 
     ' Generate output 
     MsgBox (.Name & " has " & CStr(.Children.Count) & " children named " & _ 
      .Children(1).Name & " and " & .Children(2).Name) 

    End With 


End Sub 

클래스 모듈 CmyClass에서 은 '이

Option Explicit 
Private pKey As Long 
Private pName As String 
Private pChildren As Collection 
'Define Properties 
Public Property Get Key() As Long 
    Key = pKey 
End Property 
'comment 
Public Property Get Name() As String 
    Name = pName 
End Property 
'comment 
Public Property Get Children() As Collection 
    Set Children = pChildren 
End Property 
'comment 
Public Property Let Key(p As Long) 
    pKey = p 
End Property 
' Define Methods 
Public Function Init(k As Long, sName As String) As cMyClass 
    pKey = k 
    pName = sName 
    Set pChildren = New Collection 
    Set Init = Me 
End Function 
'comment 
'comment 
+2

'mc.Key'를'Cstr (mc.Key) '로 바꾸십시오. –

+0

고마워요. – Richie10

답변

0

이미 코드를 수정 한 답이 있습니다. 그러나 향후, 두 가지주의해야 할 사항 : 목표 데이터 유형이 입력 데이터 유형과 다른 경우

  1. Run-time error 13: Type mismatch 생산 일반적인 오류입니다.

  2. 값이 숫자 인 경우에도 Collection class's key is String datatype,입니다.

+1

두 번째 링크는 VB.NET 용입니다. VBA의 경우 [Visual Basic for Applications 참조 : 컬렉션의 Add 메서드] (http://msdn.microsoft.com/en-us/library/aa265006%28v=vs.60%29.aspx)를 참조하십시오. – dee

+0

키는 문자열 데이터 유형임을 알아 두십시오. 정렬 및 필터링의 목적으로 키가 사용되므로 키를 문자열 데이터 유형으로 정의하는 것은 논리적이지 않습니다. 문자 유형으로 숫자 데이터 유형을 사용하면 정렬 및 필터링 방법이 더 빨라집니다. – Richie10

0

로가 올바른 유형 vba4all @ 지적 클래스 MODUL에 Collection Key는 문자열입니다 ...

In cMyClass

Option Explicit 
Private pKey As String 
Private pName As String 
Private pChildren As Collection 
Public myName As String 
Public Property Get Key() As String 
    Key = pKey 
End Property 
'comment 
Public Property Get Name() As String 
    Name = pName 
End Property 
'comment 
Public Property Get Children() As Collection 
    Set Children = pChildren 
End Property 
'comment 
Public Property Let Key(p As String) 
    pKey = CStr(p) 
End Property 
' Define Methods 
Public Function Init(k As Long, sName As String) As cMyClass 
    pKey = CStr(k) 
    pName = sName 
    Set pChildren = New Collection 
    Set Init = Me 
End Function 
+0

이 방법은 효과가 있지만 입력을 long으로 제한하는 목적을 변경합니다. 정렬, 필터링 등을하기 위해서만 Long-data가 필요합니다. 이제는 사용자가 숫자가 아닌 문자를 입력 할 수 없도록하는 추가 코드를 수행해야합니다. @ vba4all이 지적한 솔루션을 사용하면 데이터 유형이 그대로 유지되므로 필 요할 필요가 없습니다. – Richie10