簡體   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