重用函数的数组

我有两个不同的function,需要访问相同的数组(该数组不是一个常数,它将被编辑,并追加到该function在单元格内使用)。

我想让这个数组可用于他们两个。 该数组需要是多维的(或者是一个UDT,它可以包含多个元素,就像我在下面的代码中试过的一样),它需要能够dynamicresize。 这里有一些示例代码(编辑了一下),但它似乎没有正常工作。

Option Base 1 Private Type PathsArray Nodes() As String End Type ' Instantiate the global array Dim Paths(1 To 1) As PathsArray Function SETTWENTY() ' Increase size of the array, preserving the current elements already inside it ReDim Preserve Paths(1 To UBound(Paths) + 1) ' Make the inner array be 20 elements long ReDim Preserve Paths(UBound(Paths)).Nodes(1 to 20) ' Return something random GETPATH = UBound(Paths) End Function Function SETTHIRTY() ' Increase size of the array, preserving the current elements already inside it ReDim Preserve Paths(1 To UBound(Paths) + 1) ' Make the inner array be 30 elements long ReDim Preserve Paths(UBound(Paths)).Nodes(1 to 30) ' Return something random GETPATH = UBound(Paths) End Function 

任何人都知道为什么这不起作用?

你问题的根源在于你试图调整一个“静态”模块级别的数组。 下面是关于“静态”和“dynamic”VBAarrays之间区别的一个很好的描述(来自Chip Pearson):

http://www.cpearson.com/excel/vbaarrays.htm

你有第二个问题,你的函数将返回VBA Empty值,而不是path的数量。 在VBA中,通过将值赋给函数的名称,可以从函数返回一个值。

在下面的代码中,我解决了这些问题:

  1. 使模块级别的数组“dynamic”
  2. 添加一个“init”例程来获取你的初始元素
  3. 返回你期望的函数值

如果你原来的(1 To 1)声明实际上不是你想要的,你可能不需要(2)。

注意使用Option Explicit :(3)。 如果你在那里,那么即使在修正(1)之后,你的原始代码也会被编译成“GETPATH”。

 Option Explicit Option Base 1 Private Type PathsArray Nodes() As String End Type ' Just declare the module-level array Dim Paths() As PathsArray Public Sub init() ReDim Paths(1 To 1) As PathsArray End Sub Function SETTWENTY() ' Increase size of the array, preserving the current elements already inside it ReDim Preserve Paths(1 To UBound(Paths) + 1) ' Make the inner array be 20 elements long ReDim Preserve Paths(UBound(Paths)).Nodes(1 To 20) ' Return something random SETTWENTY = UBound(Paths) End Function Function SETTHIRTY() ' Increase size of the array, preserving the current elements already inside it ReDim Preserve Paths(1 To UBound(Paths) + 1) ' Make the inner array be 30 elements long ReDim Preserve Paths(UBound(Paths)).Nodes(1 To 30) ' Return something random SETTHIRTY = UBound(Paths) End Function 
Interesting Posts