Michi
Michi

Reputation: 5471

Keep multiple sheets visible when hiding sheets with loop

Currently, I use the following code to hide all sheets except for one (in this case Sheet4):

Sub LoopHideSheets()
    Dim b As Worksheet
    For Each b In Worksheets
        If b.CodeName <> "Sheet4" Then
            b.Visible = False
        End If
    Next b
End Sub

All this works fine so far.


Now instead of only keep Sheet4 visible I want to keep multiple sheets visible. Therefore, I tried to change the formula to this:

Sub LoopHideSheets()
    Dim b As Worksheet
    For Each b In Worksheets
        If b.CodeName <> "Sheet1" Or _
           b.CodeName <> "Sheet2" Or _
           b.CodeName <> "Sheet3" _
           Then
            b.Visible = False
        End If
    Next b
End Sub

However, this code gives me runtime error 1004. Do you have any idea where there is a mistake in my code?

Upvotes: 1

Views: 45

Answers (1)

Pᴇʜ
Pᴇʜ

Reputation: 57683

Switch the Or to And to keep sheet 1-3 visible.

The <> in a <> b negates that means it is the same as NOT a = b. This logically switches Or and And.

Upvotes: 1

Related Questions