配列ではあっても,実際のデータは存在しない配列が欲しいときがあります。
VBA では,以下のようにやると,UBound() の値が -1 の1次元配列を作れます。
Option Explicit Private Declare Sub MoveMemory Lib "Kernel32" Alias "RtlMoveMemory" _ (Destination As Any, Source As Any, ByVal Length As Long) Private Declare Function SafeArrayCreateVector Lib "OleAut32.dll" _ (ByVal vt As Integer, ByVal lLbound As Long, ByVal cElements As Long) As Long Private Type SAFEARRAYBOUND cElements As Long lLbound As Long End Type '' 要素を持たない配列を返す。 Public Function CreateArrayWithNoElement(VarType As VbVarType) As Variant Dim psa As Long Dim sab As SAFEARRAYBOUND sab.lLbound = 0 sab.cElements = 0 psa = SafeArrayCreateVector(VarType, 0, 0) If psa = 0 Then Exit Function End If Call MoveMemory(CreateArrayWithNoElement, VarType Or vbArray, 2) Call MoveMemory(ByVal VarPtr(CreateArrayWithNoElement) + 8, psa, 4) End Function
引数には,vbLong や vbString 等の VBA.VbVarType の適切な値を渡します。
Private Sub Test() Dim lngArr() As String Dim strArr() As Long Dim vntValue As Variant lngArr = CreateArrayWithNoElement(vbLong) MsgBox UBound(lngArr) strArr = CreateArrayWithNoElement(vbString) MsgBox UBound(strArr) vntValue = CreateArrayWithNoElement(vbString) MsgBox UBound(vntValue) ReDim Preserve lngArr(9) ReDim Preserve strArr(9) ReDim Preserve vntValue(9) End Sub
※ lngArr や strArr に代入時にコピーが起きますが,実際のデータは無いので気にする必要はないでしょう。
Published: 2013-03-04
Last Updated: 2013-06-14
つくれますの部屋
Copyright(C) 2013 Yasuharu Takahashi, All Rights Reserved.