excel VBA(不是VBScript)101:如何创build和读取multidimensional array?

我正在使用Excel 2010,我有一个需要将OData结果加载到内存数组的macros。 我唯一缺less的是如何在Excel中实际创build该数组。

如何在Excel 2010中创build一个multidimensional array(或一个类的数组)?

我唯一的限制就是我所创build的任何东西都必须包含在XLSX中。 所以这意味着对PowerPivot,插件等的依赖关系已经不存在了。 我认为这只是使用VBScriptmacros。

我已经search了MSDN,StackOverflow和Google几个小时,并找不到如何做到这一点的明确的例子。

作为@Jeremy的回答的扩展:

你可以redimmultidimensional array。

DIM arr() as Variant 'or object or class or whatever. Redim arr(1 To 1, 1 To 1) 'works Redim arr(1 To 3, 1 To 3) 'works, but deletes any existing data Redim Preserve arr(1 To 3, 1 To 10) 'works and keeps any data Redim Preserve arr(1 To 10, 1 To 10) 'fails, you can only redm preserve the last dimension 

无论数组,集合(或字典)是最适合您的应用程序取决于您的应用程序的细节

打开Excel

按下Alt + F11

右键单击VBAProject>插入>类

在左侧窗格的属性对话框中为VBA类“Person”指定名称

给人类一个属性,例如名字

 Public FirstName As String 

创build第二个类或模块文件,这里是如何创build/访问People类的数组:

 Public colOfPeople As New Collection Public Function MakePeople() As String Dim clsP As New clsPerson clsP.FirstName = "Jeremy" colOfPeople.Add (clsP) End Function 

解决scheme1:为了使这个多维,我做了一个数组的集合:

 Public multiColOfPeople() As New Collection Public Function MakeMultiPeople() As String ReDim Preserve colOfPeople(1) 'dimension multi-array collection Dim clsP As New clsPerson clsP.FirstName = "Jeremy" colOfPeople(0).Add (clsP) Dim clsP1 As New clsPerson clsP1.FirstName = "Lisa" colOfPeople(1).Add (clsP1) End Function 

解决scheme2:使用multidimensional array(不收集)

 Public multiArray(3, 3) As New clsPerson Dim clsP As New clsPerson 'store multiArray(0, 1) = clsP 'retrieve clsP = multiArray(0, 1) 

编辑*

要使用第二种解决scheme,请参阅Chris Neilsen对ReDim'ingmultidimensional array信息的回答