vba - 通过字典键时要求定义变量的 VBA 错误
问题描述
VBA 不断给我一条错误消息,指出未定义“键”变量。但是,这段代码曾经可以工作,我不确定为什么现在不能...
它突出显示的变量是For Each Key In dic
行上的“Key”。
为什么它给我一个错误?
'---------------------------------------------------------------------------------------
' Method : CreateUniqueISINList
' Purpose: Takes Array and groups it based on one criteria. The quantity data field is summed.
'---------------------------------------------------------------------------------------
Private Function CreateUniqueISINList(ByRef arr As Variant) As Variant
Dim dic As Dictionary
Set dic = New Dictionary
'Create dictionary with list of unique ISINs
Dim i As Long
For i = LBound(arr, 2) To UBound(arr, 2)
If Not dic.Exists(arr(1, i)) Then
dic.Add arr(1, i), arr(1, i) 'Keep ISIN
End If
Next i
'Create output Array with relevant quantity of stocks held
Dim arrWIP
ReDim arrWIP(dic.Count, 1)
Dim j As Long
For Each Key In dic
arrWIP(j, 0) = Key 'set ISIN
For i = LBound(arr, 2) To UBound(arr, 2)
If arr(1, i) = Key Then
arrWIP(j, 1) = arrWIP(j, 1) + arr(3, i) 'update quantity
End If
Next i
j = j + 1 'increase counter for arrWIP
Next Key
CreateUniqueISINList = arrWIP
Set dict = Nothing
End Function
解决方案
Dim Key
就足够了。如果你想让它看起来更好看,写Dim Key as Variant
。它以前可以工作,因为您没有明确写Option Explicit
在模块的顶部。现在,当您编写它时,您必须显式声明每个变量。
然后确保您没有 2 个具有名称dic
和dict
. 这Option Explicit
实际上可以帮助您编写更好的代码。
推荐阅读
- android - 获取空对象错误以在 recyclerView 中使用多个布局
- mongoose - 需要一个使用带静态或方法的 mockingoose 的示例
- linux - 如何制定正确的 iptable 规则,如浏览器端口配置
- clojure - 通过 Clojure 中值列表中的第一个元素获取键
- api - 在 React Native fetch 方法中解析 JSON 不起作用
- javascript - 从 ReactJS 中的其他组件打开模式
- php - foreach 在 while 循环中返回重复数据
- javascript - WebStorm 和控制台在执行上的区别
- javascript - 在 Ionic 和 Cordova 中构建 Android APK
- android-fragments - 在后台运行的android片段