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

时间:2018-07-09 07:37:23

标签: excel-vba function dictionary vba excel

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

 SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"

我发现此代码是词典和函数的示例:

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

但是,当我尝试运行makro 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 时,会显示错误消息:

  

未定义用户定义的类型

谁能告诉我我在哪里犯了错误? 预先谢谢

2 个答案:

答案 0 :(得分:0)

G'day,

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

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

Dim dict As Scripting.Dictionary

您可以如下创建对象:

Set dict = New Scripting.Dictionary

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

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

希望这会有所帮助。

答案 1 :(得分:0)

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

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。