Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to dynamically add elements in an array inside a loop

I have a workbook with several sheets and I need to create an array with only the wanted sheets.
So I have this code that skips some hardcoded sheet names, but I don’t know how to add the wanted sheets in my array ‘sheets_names_array’.
I have this code:

    ' make an array with the sheet names we want to parse
Dim sheets_names_array() As Variant, sheet As Variant

For Each ws In ThisWorkbook.Worksheets
    Select Case ws.Name
        Case "Qlik Ingestion"
            'Do nothing
        Case "Dropdown Values"
            'Do nothing
        Case "VBmacro"
            'Do nothing
        Case Else
             'MsgBox ws.Name
             sheets_names_array.Add (ws.Name)
    End Select
Next

But the ‘Add’ method doesnt work. Do you know how to solve this please?
I have seen documentation that uses ReDim but I am not sure how to loop through the elements of the ‘sheets_names_array’ table

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a collection instead

Dim sheets_names_col As New Collection

and add your items like

sheets_names_col.Add ws.Name

Dim sheets_names_col() As New Collection

Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
    Select Case ws.Name
        Case "Qlik Ingestion", "Dropdown Values", "VBmacro"
            ' do nothing
        Case Else
            sheets_names_col.Add ws.Name
    End Select
Next ws

And you can loop it like

Dim sheet As Variant
For Each sheet In sheets_names_col
    Debug.Print sheet
Next sheet
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading