VBA在Array中获取Dim的名称,索引

时间:2016-03-18 18:18:04

标签: arrays excel vba excel-vba

Sub foobar()

Dim wine As Variant
wine = Array("Red", "White", "Rose", "Sparkling")

Dim spirits As Variant
spirits = Array("Vodka", "Whiskey", "Rum", "Gin")

Dim beer As Variant
beer = Array("Ale", "Lager", "Pilsner", "Stout")

Dim inventory As Variant
inventory = Array(wine, spirits, beer)

Range("A1") = inventory(1)

End Sub

我目前的想法是将数组的名称放在数组中,

wine = Array("wine", "Red", "White", "Rose", "Sparkling")

spirits = Array("spirits", "Vodka", "Whiskey", "Rum", "Gin")

beer = Array("beer", "Ale", "Lager", "Pilsner", "Stout")

inventory = Array(wine, spirits, beer)

因此inventory(x)(0)将始终返回该数组的名称。

我希望“A1”显示Dimension的名称,即烈酒,但灵魂本身就是一个数组,因此在“A1”中我得到的是inventory(1)(0)的等价物。

有没有更好的方法让葡萄酒,烈酒或啤酒尺寸作为名称返回,而不是在数组中包含名称(如上所述)?

1 个答案:

答案 0 :(得分:3)

如果你想通过名字引用东西,那么字典是一种解决方案。

Sub foobar()

    Dim wine As Variant
    wine = Array("Red", "White", "Rose", "Sparkling")

    Dim spirits As Variant
    spirits = Array("Vodka", "Whiskey", "Rum", "Gin")

    Dim beer As Variant
    beer = Array("Ale", "Lager", "Pilsner", "Stout")

    Dim inventory As Object, k
    Set inventory = CreateObject("Scripting.Dictionary")
    With inventory
        .Add "Wine", wine
        .Add "Spirits", spirits
        .Add "Beer", beer
    End With

    'access a specific item
    Debug.Print Join(inventory("Beer"), ",")

    'loop over items
    For each k in inventory.keys
        Debug.Print k, Join(inventory(k), ",")
    Next k

End Sub