在Excel VBA中预定义多维数组

Sun*_*uza 8 excel vba excel-vba

我知道我们可以使用以下方法在excel VBA中定义单维数组

 GroupCols = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
Run Code Online (Sandbox Code Playgroud)

如何以相同的方式预定义多维数组?

此外,我想以下列方式跟踪某些级别

 Level[16][0]
 Level[16][1]
 Level[16][2]

 Level[8][0]
 Level[8][1]
 Level[8][2]

 Level[7][0]
 Level[7][1]
 Level[7][2]
Run Code Online (Sandbox Code Playgroud)

第一个索引定义了级别,因此可能不是连续的...就像16之后有直8等等.对于每个我需要3个信息,即0,1,2秒索引.

任何人都可以指导我如何在excel VBA中实现相同的目标吗?

Jea*_*ett 9

您不能在这样的数组中包含非连续索引.如果你只使用索引的非连续子集,那么所有其他元素都将为空但仍然占用存储空间,这既低效又容易出错(LaunchMissile = Levels(17,1)哎呀!).

您正在寻找的是Dictionary对象.使用前,必须按如下方式设置参考:工具>参考>检查Microsoft Scripting Runtime.

例:

Dim Levels As Scripting.Dictionary
Set Levels = New Scripting.Dictionary

' Fill up the dictionary
Levels.Add Key:=16, Item:=Array("A", "B", "C")
Levels.Add Key:=8, Item:=Array("FAI", "CNT", "YES")
Levels.Add Key:=7, Item:=Array("Once", "Twice", "Thrice")

' Retrieve items from the dictionary
Debug.Print Levels.Item(8)(0)
Debug.Print Levels.Item(8)(1)
Debug.Print Levels.Item(8)(2)
Run Code Online (Sandbox Code Playgroud)

请注意,Collection对象也可以做到这一点.优点:原生于VBA,因此无需设置参考.缺点:密钥是只写的,这可能很尴尬.


Hub*_*san 9

有一种方法可以通过使用evaluate()来定义2D数组,就像使用1D的array()一样:

Sub Array2DWithEvaluate()

Dim Array2D As Variant

'[] ist a shorthand for evaluate()
'Arrays defined with evaluate start at 1 not 0

Array2D = [{"1,1","1,2","1,3";"2,1","2,2","2,3"}]

Debug.Print Array2D(2, 2) '=> 2,2

End Sub
Run Code Online (Sandbox Code Playgroud)

如果要使用字符串来定义数组,则必须像这样使用它

Sub Array2DWithEvaluateFromString()

Dim strValues As String
Dim Array2D As Variant

strValues = "{""1,1"",""1,2"",""1,3"";""2,1"",""2,2"",""2,3""}"

Array2D = Evaluate(strValues)

Debug.Print Array2D(2, 2) '=> 2,2

End Sub
Run Code Online (Sandbox Code Playgroud)

如果您想了解更多关于函数Evaluate()的其他用途的信息,请查看这篇精彩文章.

http://www.ozgrid.com/forum/showthread.php?t=52372