尝试接收项目时出现VBA脚本.字典错误(3021)
我正在尝试使用我以前在代码中成功填充的字典,一件非常奇怪的事情正在发生。钥匙在字典里,但它不能给我值。它给出了一个错误。代码如下:尝试接收项目时出现VBA脚本.字典错误(3021),vba,dictionary,Vba,Dictionary,我正在尝试使用我以前在代码中成功填充的字典,一件非常奇怪的事情正在发生。钥匙在字典里,但它不能给我值。它给出了一个错误。代码如下: x = dict.Count For i = 2 To lastRow Key = Sheets(1).Cells(i, 8).Value If dict.Exists(Key) Then val = dictIdPrice.Item(Key) Else range("M" & i).Interior.Color = RGB(230, 0
x = dict.Count
For i = 2 To lastRow
Key = Sheets(1).Cells(i, 8).Value
If dict.Exists(Key) Then
val = dictIdPrice.Item(Key)
Else
range("M" & i).Interior.Color = RGB(230, 0, 0)
End If
Next i
“x”有一个正确的值,并且输入了If子句,但是带有现有键的Item方法给了我一个错误。我不明白为什么
复制示例的问题是,字典是从数据库中填充的,但我会尝试
Dim Key As Long
Dim val As Double
Dim Sql As String
Dim dictIdPrice
Dim lastRow As Integer
Sql = read_sql(IDs, dtFromSheet)
Dim rst As New ADODB.Recordset
Set rst = conODBC.Execute(Sql)
TotalColumns = rst.Fields.Count
records = rst.RecordCount
' check the query result is not empty etc
Set dictIdPrice = CreateObject("Scripting.Dictionary")
Do While Not rst.EOF
Key = rst.Fields(0)
If Not dictIdPrice.Exists(Key) Then
dictIdPrice.Add Key, rst.Fields(1)
End If
rst.MoveNext
Loop
For i = 2 To lastRow
Key = Trim(Sheets(1).Cells(i, 8).Value)
If dictIdPrice.Exists(Key) Then
val = dictIdPrice.Item(Key)
Else
range("M" & i).Interior.Color = RGB(230, 0, 0)
End If
Next i
键的格式为291709、289429、289823、290535290683,我猜问题出在这一行:
dictIdPrice.Add Key, rst.Fields(1)
请尝试以下方法:
dictIdPrice.Add Key, rst.Fields(1).Value
问题是,当您在字典中存储
rst.Fields(1)
时,实际上存储的是对象rst.Fields(1)
,而不仅仅是它的值。稍后,当尝试从字典中读回时,如果记录集不再指向记录,val=dcitIdPrice.Item(Key)
计算默认成员,即Value,但如果没有当前记录,则会失败。dictdprice与dict之间的差异只是一个输入错误。我引用的是同一个词典…您认为您可以提供一个可复制的示例吗?错误描述说:“BOF或EOF为True,或者当前记录已被删除。请求的操作需要一个当前记录。”这与词典问题完全无关——是您的记录集遍历导致了这一问题。查找如何正确迭代记录集以及要检查的内容-提示:rst.EOF
和MoveFirst()
我猜它与记录集有关,但在离开循环后,我已处理完记录集。如果(rst.EOF)那么rst.MoveFirst End If-这会有帮助吗?