具有并列值的VBA数组
有没有办法在VBA中定义和写入数组,使得数值对显示为两行?
fndList = Array _ ( _ "PS4", "PlayStation 4" _ "WIN", "Microsoft Windows", _ "SNES", "Super Nintendo Entertainment System" _ )
像上面的东西? 使用两个单独的数组也很好,谢谢。
你有什么(在"PlayStation 4"
之后插入缺失的逗号之后)完全有效的VBA。 但是,它会创build一个一维数组。 如果你想用类似的符号来创build一个二维数组,你可以创build一个自定义函数:
Function Matrix(m As Long, n As Long, ParamArray items()) As Variant 'Creates an mxn matrix where the items() are filled in by row Dim A As Variant Dim i As Long, j As Long ReDim A(1 To m, 1 To n) For i = 1 To m For j = 1 To n A(i, j) = items(n * (i - 1) + j - 1) Next j Next i Matrix = A End Function
用于:
Sub test() Dim fndList As Variant fndList = Matrix _ (3, 2, _ "PS4", "PlayStation 4", _ "WIN", "Microsoft Windows", _ "SNES", "Super Nintendo Entertainment System" _ ) Range("A1:B3").Value = fndList End Sub
创build的数组是基于1而不是基于0的,因为在基于Excel VBA 1的版本中,默认情况下是与范围交互。 调整函数显然很容易,所以返回的数组是基于0的。
再看看你的实际问题,如果你的目标是像"WIN"
这样的键来查找像"Microsoft Windows"
这样的值,那么你可以使用Dictionary :
Sub test2() Dim fndList As Object Set fndList = CreateObject("Scripting.Dictionary") fndList.Add "PS4", "PlayStation 4" fndList.Add "WIN", "Microsoft Windows" fndList.Add "SNES", "Super Nintendo Entertainment System" Debug.Print fndList("WIN") 'prints "Microsoft Windows" End Sub
您可以修改Matrix()
函数,以便它返回这样一个字典。 例如,像这样的东西:
Function Dict(ParamArray pairs()) As Object 'returns a dictionairy where successive pairs of 'items in the pairs array are treated as key-value 'pairs. It is assumed than an even number of items 'are passed Dim D As Object Dim i As Long, n As Long Set D = CreateObject("Scripting.Dictionary") n = (UBound(pairs) - 1) / 2 For i = 0 To n D.Add pairs(2 * i), pairs(2 * i + 1) Next i Set Dict = D End Function
哪些可以使用像:
Sub test3() Dim fndList As Object Set fndList = Dict _ ( _ "PS4", "PlayStation 4", _ "WIN", "Microsoft Windows", _ "SNES", "Super Nintendo Entertainment System" _ ) Debug.Print fndList("WIN") 'prints "Microsoft Windows" End Sub