重用具有函数的数组

时间:2011-07-20 17:30:32

标签: excel vba dijkstra

我有两个不同的函数需要访问同一个数组(该数组不是常量;只要在工作表中的单元格内使用该函数,它就会被编辑和附加。)

我想让这两个数组都可用。数组需要是多维的(或者是一个可以在其中包含多个元素的UDT,就像我在下面的代码中尝试过的那样),并且它需要能够动态调整大小。这里有一些示例代码(编辑了一下),但它似乎没有正常工作。

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

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

1 个答案:

答案 0 :(得分:1)

问题的根源在于您正在尝试调整“静态”模块级数组的大小。以下是对“静态”和“动态”VBA阵列之间差异的一个很好的描述(来自Chip Pearson):

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

您遇到的第二个问题是,您的函数将返回VBA值Empty而不是路径数。在VBA中,通过将值赋给函数名称来从函数返回值。

在下面的代码中,我通过以下方式解决了这些问题:

  1. 使模块级数组“动态”
  2. 添加“init”例程以获取您的初始元素
  3. 返回您希望从函数中获得的值
  4. 如果您的原始(1 To 1)声明不是您想要的,那么您可能并不真正需要(2)。

    请注意使用Option Explicit re:(3)。如果你有那个,你的原始代码与“GETPATH”分配将无法编译,即使在修复(1)之后。

    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