从VBA字典

时间:2017-08-07 21:34:04

标签: excel vba excel-vba

我已通过下面缩写的方法在数据列表中找到了唯一值:

Dim dictionary as scripting.dictionary
Dim data() as String
Dim dataSize as Integer
Dim j as integer
Dim v as variant

DataSize = myRange.Rows.Count

Redim data(dataSize)
For j = 1 to UBound(data)
data(j) = myRange.Cells(j,1).Value
dictionary(data(j)) = 1
Next j

这应该将myRange中的唯一值存储为Key值。但是,我似乎无法弄清楚如何访问这些值。我尝试过以下方法:

For each v in dictionary.Keys()
myVar = v
'dostuff to myVar
next v

For each v in dictionary.Keys()
myVar = dictionary.Keys(v)
'dostuff to myVar
next v

但不起作用。我错过了什么?

1 个答案:

答案 0 :(得分:0)

添加Set dictionary = New dictionary,然后您可以循环:

Sub t()
Dim dictionary     As Scripting.dictionary
Dim data()  As String
Dim dataSize As Integer
Dim j       As Integer
Dim v       As Variant

dataSize = myRange.Rows.Count
Set dictionary = New dictionary

ReDim data(dataSize)
For j = 1 To UBound(data)
    data(j) = myRange.Cells(j, 1).Value
    dictionary(data(j)) = 1
Next j

Dim i As Long
For i = 0 To dictionary.Count - 1
    Debug.Print dictionary.Keys()(i) & " " & dictionary.Items()(i)
Next i
End Sub