2017-05-29 111 views
0

有沒有辦法在VBA中定義和寫入數組,以便將數值對顯示爲兩行?具有並排值的VBA陣列

fndList = Array _ 
(_ 
    "PS4", "PlayStation 4" _ 
    "WIN", "Microsoft Windows", _ 
    "SNES", "Super Nintendo Entertainment System" _ 
) 

就像上面那樣?謝謝,使用兩個單獨的數組也很好。

+1

爲什麼不考呢?如果你在「PlayStation 4」之後立即輸入一個逗號,那麼你所擁有的是完全有效的VBA。你的實際數據看起來似乎最適合於'Dictionary'。 –

+1

看起來你缺少一個逗號。你想創建一個'fndList(1到3,1到2)'數組嗎? – Jeeped

+0

錯過的逗號確實是這個問題,謝謝! – posfan12

回答

1

你有什麼是(在"PlayStation 4"之後插入缺失的逗號)完全有效的VBA。但是,它會創建一維數組。如果你想類似的標記來創建一個2維數組,你可以創建自定義功能:

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 

其中創建數組是從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 
+0

如何迭代字典? – posfan12

+1

@ posfan12您可以使用'for-each'循環,如下所述:https://stackoverflow.com/q/1296225/4996248。請注意,循環索引應該是一個變體。這是一個很好的字典教程:https://excelmacromastery.com/vba-dictionary/。如果你想走這條路線,希望我在上次編輯中添加的功能會有幫助。 –