ray88’s diary

お仕事で困ったとき用の自分用の覚書

VBA Collectionを戻り値として渡す

参考URL:VBAメモ メソッドでCollectionを戻り値で返してみる | tetsuyanbo
■サンプルコード①
【呼び出し元プロシージャ】

Option Explicit

Sub コレクションテスト()
    Dim testCo As Collection
    Dim maxNum As Integer
    Dim i As Integer
    
    Set testCo = MakeCollection()
    maxNum = testCo.Count
    
    For i = 1 To maxNum
        MsgBox testCo(i)
    Next
End Sub

【Functionプロシージャ】

Function MakeCollection() As Collection
    Dim Col As Collection
    Set Col = New Collection
    
    With Col
        .Add "りんご"
        .Add "みかん"
        .Add "ばなな"
    End With
    
   Set MakeCollection = Col
   
End Function

■サンプルコード2
【呼び出し元プロシージャ】

Sub コレクションテスト()
    Dim testCo As Collection
    Dim maxNum As Integer
    Dim v As Variant
    Set testCo = MakeCollection("りんご", "みかん", "ばなな")
    maxNum = testCo.Count
    For Each v In testCo
        MsgBox v
    Next
End Sub

【Functionプロシージャ】

Function MakeCollection(strItem1 As String, strItem2 As String, strItem3 As String) As Collection
    Dim Col As Collection
    Dim num As Integer
     Set Col = New Collection    
    With Col
        .Add strItem1
        .Add strItem2
        .Add strItem3
    End With    
    num = Col.Count    
    If num = 0 Then
        Col.Add "アイテムなし"
    End If    
    Set MakeCollection = Col
End Function