vba - 在 VBA 中向集合添加键

标签 vba excel

在向集合添加 key 时,我遇到了一个奇怪的问题。 运行时错误13:类型不匹配

模块代码:

'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

最佳答案

您已经有了修复代码的答案。但展望 future ,有两件事需要注意:

  1. Run-time error 13: Type mismatch是当目标数据类型与输入数据类型不同时产生的常见错误。

  2. 那个Collection class's key is String datatype,即使值是数字。

关于vba - 在 VBA 中向集合添加键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27915917/

相关文章:

excel - 可以使用两个变量给出 vba 的单元格编号吗

excel - 使用另一个单元格值引用范围

excel - 使用 VBA 将 MS Project 转换为 Excel 甘特图

excel - Excel.ThisWorkbook 和 ThisWorkbook 之间的区别?

excel - 在Excel 2010中的下拉列表中创建一个复选框

excel - 为什么第一个随机数总是一样的?

excel - 复选框 "Trust access to the VBA Project Model"是什么意思?

vba - 复制粘贴过滤的数据未按预期工作

vba - 连接 PowerPoint 和 Excel

excel - 将一个大的 xls 文件读入 R