2011-07-20 21 views
1

同じ配列へのアクセスを必要とする2つの異なる関数があります(配列は定数ではなく、シート内のセル内で関数が使用されるたびに編集および追加されます)。関数を使用した配列の再利用

この配列を両方で使用できるようにしたいと考えています。配列は多次元(または、私のコードで試したような複数の要素を持つことができる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. 返しますあなたの関数から期待される値

    元の(1 To 1)宣言があなたがとにかく欲しかったものではない場合は、本当に(2)を必要としないかもしれません。

    re:(3)の使用に注意してください。もしあなたがそこにいたのであれば、 "GETPATH"割り当てを持つオリジナルのコードは、fix(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 
    
  • +0

    詳細な説明をいただきありがとうございます。私はあなたの助けを借りて問題を整理することができました! – Steve

    関連する問題