繁体   English   中英

字典和函数:未定义用户定义的类型

[英]dictionarys and functions: User-defined type not defined

我已经在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 ,会显示错误消息:

用户定义类型未定义

谁能说出我在哪里犯错了? 先感谢您

G'day,

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

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

Dim dict As Scripting.Dictionary

您可以如下创建对象:

Set dict = New Scripting.Dictionary

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

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

希望这可以帮助。

您也可以像这样晚绑定代码:

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM