【ExcelVBA】クラスモジュール の Property Let/Get に配列を使う

ExcelVBA,クラスの操作

クラスモジュール内で配列を使う方法

Class1 の内容


Private Arr(0 To 100) As Long

Property Let Values(i As Long, value As Long)
		Arr(i) = value
End Property

Property Get Values(i As Long) As Long
		Values = Arr(i)
End Property

標準モジュール(Module1) の内容


Sub Sample1()

    Dim ClsTest As Class1: Set ClsTest = New Class1

    ClsTest.Values(0) = 5 'Property Let Values(0, 5) 
    ClsTest.Values(1) = 7 'Property Let Values(1, 7) 
    
    Debug.Print ClsTest.Values(0) 'Property Get Values(0) As Long
    Debug.Print ClsTest.Values(1) 'Property Get Values(1) As Long

End Sub

実行結果

5
7

標準モジュール内で配列を使う方法

次はインスタンスを複数生成するバージョン。けど、実用的ではありませんね。

Class2 の内容


Private OutValue As Double

Property Let DoubleNumber(InValue As Double)
    OutValue = InValue
End Property

Property Get DoubleNumber() As Double
    DoubleNumber = OutValue
End Property

標準モジュール(Module2) の内容


Dim ClsTest() As Class2

Sub Sample2()
    
    ReDim Preserve ClsTest(1)
    
    Set ClsTest(0) = New Class2   'インスタンス生成
    Set ClsTest(1) = New Class2   'インスタンス生成
           
    ClsTest(0).DoubleNumber = 1.1
    ClsTest(1).DoubleNumber = 9.9
    
    Debug.Print ClsTest(0).DoubleNumber
    Debug.Print ClsTest(1).DoubleNumber
    
End Sub

実行結果

1.1
9.9

クラスモジュール内で配列(ReDim Preserve)を使う方法

コメント頂いた 風韻さん のアイデアです。とても柔軟に扱えるのでおすすめです。ありがとうございます(^_^)

Class1 の内容


Dim Arr() As Variant

Property Let Values(i As Long, value As Long)
    ReDim Preserve Arr(i)
    Arr(i) = value
End Property
 
Property Get Values(i As Long) As Long
    Values = Arr(i)
End Property

標準モジュール(Module1) の内容


Sub Sample3()
 
    Dim ClsTest As Class1: Set ClsTest = New Class1
 
    ClsTest.Values(0) = 20 'Property Let Values(0, 20)
    ClsTest.Values(1) = 14 'Property Let Values(1, 14)
     
    Debug.Print ClsTest.Values(0) 'Property Get Values(0) As Long
    Debug.Print ClsTest.Values(1) 'Property Get Values(1) As Long

End Sub

実行結果

20
14