首页 > 解决方案 > 通过字典键时要求定义变量的 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

标签: vbaexcel

解决方案


Dim Key就足够了。如果你想让它看起来更好看,写Dim Key as Variant。它以前可以工作,因为您没有明确写Option Explicit在模块的顶部。现在,当您编写它时,您必须显式声明每个变量。

然后确保您没有 2 个具有名称dicdict. 这Option Explicit实际上可以帮助您编写更好的代码。


推荐阅读