如何使用Excel VBA将值推入非特定数组大小

我正在寻求帮助,推动从基于某些filter/单词匹配的XML的值parsing到一个数组列表。 但是,此数组不应具有预定义的数组大小,因为XMLinput是从文件到文件的dynamic。 含义是,XML文件1可能有10个这样的input,XML文件2可能有15个input。 有人可以告诉我如何能做下面2things:

  1. 如何通过预定义数组大小来定义数组列表? 当用户逐个读取节点时,大小取决于XMLinput列表
  2. 当findXML字匹配时,会将xmlinput/值parsing到Excel VBA中并保留在该数组中。

数组可以像定义一样

 Dim MyArray() as string 

然后在运行时resize和重新resize

 Redim MyArray(lb to ub) 

或者保留数组中的任何现有数据

 Redim Preserve MyArray(lb to ub) 

lb和ub是数组的边界,可以由代码确定,例如

 lb = 1 ub = <number of matched found in xml> 

逐步resize

 redim MyArray (0 to 0) For each line in xml if Match then MyArray(ubound(MyArray)) = Match Redim Preserve MyArray(0 to ubound(MyArray) + 1) end if Next ' Array ends up 1 size larger than number of matches ' if ubound(MyArray) > 0 then redim Preserve MyArray (0 to ubound(MyArray) - 1) end if 

尽pipe听起来很愚蠢,但是有时使用一个可以被看作是一个dynamic的sorting数组的string是有用的,然后将其拆分。 这种方法只有在你的结果数组中的对象是string或数字,并且你可以确信char。 您select作为分隔符的顺序不会出现在对象的任何string表示中,例如:

 Temp = "" Separator = "," For A = 1 to 155 If Temp <> "" Then Temp = Temp & Separator End If Temp = Temp & CStr(A) Next 'A myArray = Split(Temp, Separator) 'now myArray has the elements 1, 2, ..., 155 (which are strings!) 

这在某些特殊情况下可能有用,因为它是一种更直观的方式。 请注意,以这种方式创build的数组是一个string数组!