2011-07-20 71 views
1

我有兩個不同的函數需要訪問同一個數組(該數組不是常數;只要函數在表單中的某個單元格內使用,它就會被編輯和追加)。重用函數數組

我想使這個數組可用於他們兩個。該數組需要是多維的(或者是一個可以包含多個元素的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

問題的根源在於您試圖調整「靜態」模塊級別數組的大小。這裏是「靜態」和「動態」 VBA陣列之間的差異的一個很好的說明(從芯片皮爾遜):

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

你有一個次要問題,即你的函數將返回VBA價值Empty代替路徑的數量。在VBA中,通過將值賦給函數的名稱,可以從函數返回一個值。

  1. 使模塊級陣列「動態」
  2. 添加的「init」例行程序來獲取初始元件在那裏
  3. 返回:

    在下面的代碼,我通過固定這些問題您期望從您的功能值

如果您的原始(1 To 1)聲明不是真的想要什麼,您可能不需要(2)。

請注意使用Option Explicit re:(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 
+0

感謝您的詳細解釋!我設法解決您的幫助問題! – Steve