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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With