我有一組稱為“鍵”的組合。我想檢查 I 列中是否存在每個組合,如果存在,則將現有組合拆分為 2 個字串,并將它們作為一對添加到我的字典“combiExist”中。我的代碼拋出 457 錯誤
Dim combiExist As Object
Set combiExist = CreateObject("Scripting.Dictionary")
For Each cle In keys
'If combination exists in my range
If Not .Range("I:I").Find(cle) Is Nothing Then
'Split string from 7th position, left part is the key, right part is the value
combiExist.Add Left(cle, 7), Right(cle, 7)
End If
Next
我該如何解決這個問題?
uj5u.com熱心網友回復:
錯誤 457 表示該鍵已與集合的元素相關聯。因此,在將其分配給字典之前,請確保它不存在,帶有.Exists. 這個作業相當不錯,最后它列印字典:
Sub Main()
Dim combiExist As Object
Set combiExist = CreateObject("Scripting.Dictionary")
Dim combinations As Variant
combinations = Array("joeC12345678910", "C12345678910", "foooooo123")
Dim cle As Variant
For Each cle In combinations
If Not Worksheets(1).Range("I:I").Find(cle) Is Nothing Then
If combiExist.exists(Left(cle, 7)) Then
Debug.Print "Do nothing this one " & (Left(cle, 7)) & " exists!"
Else
combiExist.Add Left(cle, 7), Right(cle, 7)
End If
End If
Next
PrintDictionary combiExist
End Sub
Public Sub PrintDictionary(myDict As Object)
Dim key As Variant
For Each key In myDict.keys
Debug.Print key; "-->"; myDict(key)
Next key
End Sub
一般來說,不要使用Keys變數名之類的詞,因為這在 VBA 中意味著某些東西——通常是給定字典的鍵的集合。你可以看到myDict.keysin的實作PrintDictionary()。
uj5u.com熱心網友回復:
謹防巫毒編程
Do
If Inp.AtEndOfStream = True then exit do
Line=Inp.readline
On Error Resume Next
Dict.Add(Line, "")
If err.number = 457 then err.clear
On Error Goto 0
Loop
這是一種編程方式。一個人做并處理它。
using 給出的答案會.exists產生不必要的函式呼叫。所有方法和屬性都是底層的間接函式呼叫。這意味著堆疊設定和拆除。如果重復,每個專案將至少有一個功能。但是對于獨特的專案會有兩個函式呼叫。
測驗回傳值每個專案只有一個功能。
還要記住 every.也是一個函式呼叫。
記住 COM 方法/屬性看起來像這樣
Err.Number = MethodName(Param1, ..., ReturnValue)
Err.NumberHResult,在 COM 中稱為 an ,回傳有關您的呼叫的資訊。
擁抱錯誤。
堆疊上有什么。
回傳地址、回傳值、任何引數(輸入或輸出)和所有區域變數。
在另一個答案中,至少有 3 個函式呼叫或 4 個(如果不存在)。
如果存在與否,我的代碼為 2。這是乘以專案的數量。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492097.html
