Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA: For loop used for an array gives error

Tags:

excel

vba

This following code gives me "For each control variable on arrays must be Variant" error. But ws_names is an array of variant, if I'm not mistaken. Can someone please explain? Thank you!

Public Sub test12()
    Dim ws_names() As Variant
    ws_names = Array("Sheet2", "Sheet3")
    Dim ws_name As String
    For Each ws_name In ws_names()
        ThisWorkbook.Worksheets(ws_name).Visible = False
    Next ws_name
End Sub
like image 631
Garry W Avatar asked Sep 16 '26 10:09

Garry W


2 Answers

You don't need to loop through the array

Dim ws_names() As Variant
ws_names = Array("Sheet2", "Sheet3")

Sheets(ws_names).Visible = False

You can also use a one liner

Sheets(Array("Sheet2", "Sheet3")).Visible = False
like image 83
GMalc Avatar answered Sep 18 '26 00:09

GMalc


The syntax of a For Each...Next Statement loop is: For Each element in group ... Next element

For collections, element can only be a Variant variable, a generic object variable, or any specific object variable. For arrays, element can only be a Variant variable.

Thus, the following would work:

Public Sub test12()
    Dim ws_names() As Variant
    ws_names = Array("Sheet2", "Sheet3")
    Dim ws_name As Variant
    For Each ws_name In ws_names()
        ThisWorkbook.Worksheets(ws_name).Visible = False
    Next ws_name
End Sub

However, as @GMalc pointed out in their answer, a loop is not even necessary for this one.

like image 41
Valon Miller Avatar answered Sep 18 '26 00:09

Valon Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!