Custom Collection Classのすすめ(1)

Custom Collection Classのすすめ(1)

PersonクラスとPersonsクラス

ちょっと次のコードをご覧いただきたい。

リスト1
Private Sub test01()
  Dim proWrestlers As Persons
  Set proWrestlers = New Persons
  With proWrestlers
    Call .Add
    Call .Add("阿修羅原", "ラリアート")
    Call .Add("平田淳嗣")
  End With
  Dim pw As Person
  For Each pw In proWrestlers
    With pw
      Debug.Print .Name & " : " & .FavoriteHold
    End With
  Next
End Sub

ちょっとだけ解説すると、PersonPersonsという自作のクラスがあり、PersonオブジェクトのAddメソッドを実行すれば、PersonsオブジェクトにPersonオブジェクトが追加されるようにしている。

この説明だけ見れば、丁度Personsコレクションの要素がPerson オブジェクト、という関係である。

で、上掲コードの

For Each pw In proWrestlers
  With pw
    Debug.Print .Name & " : " & .FavoriteHold
  End With
Next

の部分。

変数pwにはPersonクラスのインスタンスが入り、変数proWrestlersにはPersonsクラスのインスタンスが入っている。

で、通常このリスト1を実行するとどうなるか。

f:id:akashi_keirin:20200229141009j:plain

当然こうなるのである。

原因は

f:id:akashi_keirin:20200229141012j:plain

当然ここ。

Personsは所詮勝手に作ったクラスに過ぎず、Collectionではないからだ。

For Eachが使える?!

ところが、『VBA Developer's Handbook Second Edition』で紹介されていたテクニックをちょこちょこっと使うと、

f:id:akashi_keirin:20200229141030g:plain

こんなふうにフツーに動く。

まるで、PersonsオブジェクトがPersonオブジェクトのCollectionであるかのように振る舞うのである!

おわりに

ちょっとスゴくないですか?

次回に続く!

続かないかも知れんけどw