我想做的事情相当简单。我想获得Dictionary
中所有项(值)的列表,并将它们保存在字符串数组中。
我猜这段代码会起作用:
Sub PrintFilters(ByVal crit As Dictionary)
Dim i() As String
i = crit.Items()
' Do stuff with i
End Sub
但是,我在第三行遇到类型不匹配。我猜测crit.Items()
的返回值是某种列表,而不是数组。但是,MSDN页面没有提到此方法的返回值类型是什么。
有没有正确的方法呢?
答案 0 :(得分:6)
我认为是Variant类型所以试试这个:
Sub PrintFilters(ByVal crit As Dictionary)
Dim i As Variant
i = crit.Items()
' Do stuff with i
End Sub
答案 1 :(得分:5)
如果您需要字符串数组,则需要手动构建一个字符串数组,因为.Items
是variant()
Sub PrintFilters(crit As Dictionary)
Dim key As Variant, i As Long
ReDim items(crit.Count - 1) As String
For Each key In crit.Keys()
items(i) = crit(key)
i = i + 1
Next
Debug.Print Join(items, ", ")
End Sub
答案 2 :(得分:0)
请在下面找到两个获得相同结果的选项,方法是将转换直接作为主例程的一部分处理,或者将字典传递给返回字符串数组的函数;在VBA本地窗口中的检查表明arrString
是类型为“ String(0 to 2)”的变量。请注意,可以使用字典.Keys
或.Items
来构建数组。
在第一个示例中,Join
函数创建了一个字符串,其中包括用aDict.Items
字符分隔的所有"|"
。然后,Split
函数将该字符串分解为字符串数组,其中"|"
用作创建每个数组元素的定界符。
在两个示例中,从字典到字符串数组的实际转换都是通过1行代码实现的。
选项1-作为主例程的一部分
Sub Dictionary_to_StringArray()
Dim aDict As Scripting.Dictionary
Dim arrString() As String
Set aDict = New Scripting.Dictionary
aDict.Add "United Kingdom", "London"
aDict.Add "France", "Paris"
aDict.Add "United States of America", "Washington, D.C."
arrString = Split(Join(aDict.Items, "|"), "|") 'this works equally with .Items & .Keys
Set aDict = Nothing
Erase arrString
End Sub
选项2-专用功能处理的转换
Sub CallingProc()
Dim aDict As Scripting.Dictionary
Dim arrString() As String
Set aDict = New Scripting.Dictionary
aDict.Add "United Kingdom", "London"
aDict.Add "France", "Paris"
aDict.Add "United States of America", "Washington, D.C."
arrString = Make_StringArray_From_Dictionary(aDict)
Set aDict = Nothing
Erase arrString
End Sub
Function Make_StringArray_From_Dictionary(ByVal SubmitDict As Scripting.Dictionary) As String()
Make_StringArray_From_Dictionary = Split(Join(SubmitDict.Items, "|"), "|")
End Function