Converting VBA Collection to Array

前端 未结 3 1618
情话喂你
情话喂你 2020-12-10 08:16

I am trying to create an array with all the worksheet names in my workbook that have the word \'Template\' in it. I thought the easiest way to do this would be to create a c

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 09:11

    This is my collectionToArray function:

    Public Function CollectionToArray(myCol As Collection) As Variant
    
        Dim result  As Variant
        Dim cnt     As Long
    
        ReDim result(myCol.Count)
        For cnt = 0 To myCol.Count - 1
            result(cnt) = myCol(cnt + 1)
        Next cnt
        CollectionToArray = result
    
    End Function
    

    It is better than the one you are using, because it will not give an error, if the collection is empty. To avoid the error on an empty collection in your case, you may consider adding a check like this:

    If col.Count > 0 Then k = CollectionToArray(col)
    

提交回复
热议问题