'標準モジュール
Sub CollectionTest()
Dim owner As Class1 'ownerクラスインスタンス用
Dim mypet As Class1 'mypetクラスインスタンス用
'Worksheetオブジェクト設定
Dim ws As Worksheet: Set ws = Sheet1
'コレクションオブジェクト作成
Dim mycol As Collection: Set mycol = New Collection
Dim i As Long: i = 4 '4行目からデータなので初期化
With ws
Do While .Cells(i, 1).Value <> ""
'ownerとmypetインスタンス作成
Set owner = New Class1
Set mypet = New Class1
'ownerクラスのプロパティ
owner.ID = .Cells(i, 1).Value 'IDに代入
owner.Name = .Cells(i, 2).Value 'Nameに代入
owner.Age = .Cells(i, 3).Value 'Ageに代入
'mypetクラスのプロパティ
mypet.Name = .Cells(i, 4).Value 'mypetのNameに代入
mypet.Age = .Cells(i, 5).Value 'mypetのAgeに代入
mypet.Types = .Cells(i, 6).Value 'Tipesに代入
mypet.Gender = .Cells(i, 7).Value 'Genderに代入
Set owner.Pet = mypet 'owner.Typeにmypetを代入
'コレクションにインスタンスを追加
mycol.Add owner, owner.ID
i = i + 1
Loop
End With
'Item毎の保存データをメッセージで表示して確認
For i = 1 To mycol.Count
With mycol(i)
MsgBox "OWNER:" & .Name & "(" & .Age & "歳)" _
& vbCrLf & "ペット名:" & .Pet.Name & _
"(" & .Pet.Age & "歳)" & .Pet.Types & _
"/" & .Pet.Gender
End With
Next
'不要になったオブジェクトを解放
Set ws = Nothing
Set mycol = Nothing
End Sub
'クラス内変数はPrivateで宣言
Private sID As String
Private sName As String
Private iAge As Integer
Private sTypes As String
Private sGender As String
Private cPet As Class1
'ID(ID)プロパティ取得
Public Property Get ID() As String
ID = sID
End Property
'名前(Name)プロパティ設定
Public Property Let ID(ByVal IDValue As String)
sID = IDValue
End Property
'名前(Name)プロパティ取得
Public Property Get Name() As String
Name = sName
End Property
'名前(Name)プロパティ設定
Public Property Let Name(ByVal nameValue As String)
sName = nameValue
End Property
'年齢(Age)プロパティ取得
Public Property Get Age() As Integer
Age = iAge
End Property
'年齢(Age)プロパティ設定
Public Property Let Age(ByVal ageValue As Integer)
iAge = ageValue
End Property
'ペット種類(Types)プロパティ取得
Public Property Get Types() As String
Types = sTypes
End Property
'ペット種類(Types)プロパティ設定
Public Property Let Types(ByVal typesValue As String)
sTypes = typesValue
End Property
'ペット性別(Gender)プロパティ取得
Public Property Get Gender() As String
Gender = sGender
End Property
'ペット性別(Gender)プロパティ設定
Public Property Let Gender(ByVal genderValue As String)
sGender = genderValue
End Property
'Petプロパティ取得
Public Property Get Pet() As Class1
Set Pet = cPet
End Property
'Petプロパティ設定
Public Property Set Pet(ByVal petValue As Class1)
Set cPet = petValue
End Property
【クラスモジュールのコード解説】
・2~7行目、クラス内で使用する変数をPrivateで定義しています。
・10~48行目までは各プロパティの設定です。
・54~56行、Property Set Pet で変数 cPet に(引数の)myPetクラスを設定します。
・50~52行目、Property Get Pet で名前(Pet)プロパティの値cPetを取得します。