【问题标题】:dictionarys and functions: User-defined type not defined字典和函数:未定义用户定义类型
【发布时间】:2018-07-09 16:57:28
【问题描述】:

我在 Excel VBA 中输入了以下代码: 该函数应该根据某个列部分中的唯一值创建一个字典。

Function CreateDictForFactors(xcord As Integer, ycord As Integer, length As Integer) As Dictionary
Dim Dict As Dictionary
Set Dict = New Dictionary
Dim i As Integer
For i = 0 To length - 1
If Not Dict.Exists(Cells(xcord + i, ycord)) Then
            Dict.Add Cells(xcord + i, ycord), 0
            End If
Next i
Set CreateDictForFactors = Dict
End Function

Sub test2()
Dim dict1 As Dictionary
Set dict1 = CreateDictForFactors(7, 6, 12)

End Sub

我发现此代码可作为字典和函数的示例:

Sub mySub()
    dim myDict as Dictionary
    set myDict = myFunc()
End Sub

Function myFunc() as Dictionary
    dim myDict2 as Dictionary
    set myDict2 = new Dictionary
            'some code that does things and adds to myDict2'
    set myFunc=myDict2
End Function

但是,当我尝试运行 makro test2 时,它会给出错误消息:

用户自定义类型未定义

谁能告诉我哪里出错了? 提前谢谢你

【问题讨论】:

标签: excel function dictionary vba


【解决方案1】:

生日,

您是否添加了“Microsoft Scripting Runtime”作为对您项目的引用?

完成后,将 dict 声明为 Scripting.Dictionary,如下所示:

Dim dict As Scripting.Dictionary

您可以按如下方式创建对象:

Set dict = New Scripting.Dictionary

这是一个描述字典使用的好网站:

https://excelmacromastery.com/vba-dictionary/

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    你也可以像这样后期绑定代码:

    Function CreateDictForFactors(xcord As Integer, ycord As Integer, length As Integer) As Dictionary
    Dim Dict As Object
    Set Dict = CreateObject("Scripting.Dictionary")
    Dim i As Integer
    For i = 0 To length - 1
    If Not Dict.Exists(Cells(xcord + i, ycord)) Then
                Dict.Add Cells(xcord + i, ycord), 0
                End If
    Next i
    Set CreateDictForFactors = Dict
    End Function
    
    Sub test2()
    Dim dict1 As Object
    Set dict1 = CreateDictForFactors(7, 6, 12)
    
    End Sub
    

    请注意,这两种方法都不适用于 Mac。

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      相关资源
      最近更新 更多