在VB.NET中,我可以遍历字典的键/值对:
Dictionary<string, string> collection = new Dictionary<string, string>();
collection.Add("key1", "value1");
collection.Add("key2", "value2");
foreach (string key in collection.Keys)
{
MessageBox.Show("Key: " + key + ". Value: " + collection[key]);
}
我知道在VBA中我可以遍历Collection对象的 values :
Dim Col As Collection
Set Col = New Collection
Dim i As Integer
Col.Add "value1", "key1"
Col.Add "value2", "key2"
For i = 1 To Col.Count
MsgBox (Col.Item(i))
Next I
我也知道我使用Scripting.Dictionary VBA对象执行此操作,但我想知道这是否可以用于集合。
我可以遍历VBA集合中的键/值对吗?
答案 0 :(得分:29)
您无法从集合中检索密钥的名称。相反,您需要使用字典对象:
Sub LoopKeys()
Dim key As Variant
'Early binding: add reference to MS Scripting Runtime
Dim dic As Scripting.Dictionary
Set dic = New Scripting.Dictionary
'Use this for late binding instead:
'Dim dic As Object
'Set dic = CreateObject("Scripting.Dictionary")
dic.Add "Key1", "Value1"
dic.Add "Key2", "Value2"
For Each key In dic.Keys
Debug.Print "Key: " & key & " Value: " & dic(key)
Next
End Sub
答案 1 :(得分:0)
这个答案不是迭代集合的键——这似乎是不可能的,但如果你不想使用字典,它会提供更多的解决方法。
您可以执行 https://stackoverflow.com/a/9935108/586754 中概述的 KeyValues 集合。 (创建键值类并将它们放入集合中。)
在我的(非 Excel 但 SSRS)案例中,我无法添加类,也不想添加 .net 引用。
我使用了 2 个集合,1 个用于存储键,1 个用于存储值,然后在添加或删除时保持它们同步。
以下以添加为例 - 尽管它仅限于字符串/int 键/值,并且 int 值未存储但添加到以前的值中,这是我在 SSRS 中聚合值所需要的。这可以很容易地修改,但不是添加而是存储值。
ck key 集合,cv 值集合。
Private Sub StoreAdd(ck As Collection, cv As Collection, k As String, v As Integer)
Dim i As Integer
Dim found As Boolean = false
Dim val As Integer = v
For i = 1 to ck.Count
if k = ck(i)
' existing, value is present
val = val + cv(i)
' remove, will be added later again
ck.Remove(i)
cv.Remove(i)
End If
if i <= ck.Count
' relevant for ordering
If k > ck(i)
' insert at appropriate place
ck.Add(k, k, i)
cv.Add(val, k, i)
found = true
Exit For
End If
End If
Next i
if not found
' insert at end
ck.Add(k, k)
cv.Add(val, k)
End If
End Sub