Converting VBA Collection to Array

前端 未结 3 1622
情话喂你
情话喂你 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 08:51

    It's all there, you're just not using the Function as a function. You need to store the result in something, like 'NewArray'..?

    Public col As New Collection
    Public Sub Test()
    For Each ws In ThisWorkbook.Worksheets
        If InStr(ws.Name, "Template") <> 0 Then
            col.Add ws.Name
        End If
    Next ws
    
    
    ' Tweaked as per Vityata's comment
    
    If col.Count > 0 Then 
        newarray = collectionToArray(col)
    Else
        ' Do something else
    End If
    
    End Sub
    
    Function collectionToArray(c As Collection) As Variant()
        Dim a() As Variant: ReDim a(0 To c.Count - 1)
        Dim i As Integer
        For i = 1 To c.Count
            a(i - 1) = c.Item(i)
        Next
        collectionToArray = a
    End Function
    

提交回复
热议问题