Excel 字典和函数:未定义用户定义的类型
我在Excel VBA中键入了以下代码: 函数应该根据特定列部分中的唯一值创建字典Excel 字典和函数:未定义用户定义的类型,excel,function,dictionary,vba,Excel,Function,Dictionary,Vba,我在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(
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
但是,当我尝试运行makrotest2
时,它会给出错误消息:
未定义用户定义的类型
谁能告诉我哪里出错了?
提前谢谢你G'day
是否添加了“Microsoft脚本运行时”作为项目的参考
完成后,将dict声明为脚本。字典如下:
Dim dict As Scripting.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
可以按如下方式创建对象:
Set dict = New Scripting.Dictionary
这是一个介绍词典使用的好网站:
希望这有帮助。您也可以像这样延迟绑定代码:
Dim dict As Scripting.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