私はこの障害にぶつかりながら、この質問に出くわしました。ReDim Preserve
私は、新しいサイズの配列 (最初または最後の次元) でこれを処理するコードを非常に迅速に作成することになりました。たぶん、同じ問題に直面している他の人を助けるでしょう。
したがって、使用法として、最初に配列を として設定し MyArray(3,5)
、次元を (最初も!) 大きくしたいとしMyArray(10,20)
ます。このようなことをするのに慣れているでしょう?
ReDim Preserve MyArray(10,20) '<-- Returns Error
残念ながら、最初の次元のサイズを変更しようとしたため、エラーが返されます。したがって、私の関数では、代わりに次のようにするだけです。
MyArray = ReDimPreserve(MyArray,10,20)
これで配列が大きくなり、データが保持されます。多次元ReDim Preserve
配列の作成は完了です。:)
そして最後になりましたが、奇跡的な機能:ReDimPreserve()
'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve,nNewFirstUBound,nNewLastUBound)
ReDimPreserve = False
'check if its in array first
If IsArray(aArrayToPreserve) Then
'create new array
ReDim aPreservedArray(nNewFirstUBound,nNewLastUBound)
'get old lBound/uBound
nOldFirstUBound = uBound(aArrayToPreserve,1)
nOldLastUBound = uBound(aArrayToPreserve,2)
'loop through first
For nFirst = lBound(aArrayToPreserve,1) to nNewFirstUBound
For nLast = lBound(aArrayToPreserve,2) to nNewLastUBound
'if its in range, then append to new array the same way
If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
aPreservedArray(nFirst,nLast) = aArrayToPreserve(nFirst,nLast)
End If
Next
Next
'return the array redimmed
If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
End If
End Function
20分くらいで書いたので保証はありません。ただし、使用したり拡張したりしたい場合は、お気軽に。誰かがこのようなコードをすでにここに持っていると思っていたでしょうが、明らかにそうではありません。それでは、仲間のギアヘッドに行きましょう。