简体   繁体   中英

Hide non-active worksheets in Excel VBA

I have a UserForm in Excel 2013 that cleans up the Excel page for the user prior to manipulation. The public Module has the following VBA code:

Sub ShowForm()
    With ActiveWorkbook
        .Worksheets("Sheet1").Activate
        .Worksheets("Sheet2").Visible = False 'Hide didn't work
        .Worksheets("Sheet3").Visible = False 'Hide didn't work
    End With

    UserForm1.Show
End Sub

How can I hide Worksheets 2 and 3 and activate or make Worksheet 1 visible? The code should mimic right-clicking a tab and selecting "Hide". The above code throws a Run-time error '9': Subscript out of range .

Looks like you're after hiding everything except the active sheet. Try this code - it doesn't depend on the sheet name.

Sub Test()

    SheetVisibility 'Hide all except active sheet.

    MsgBox "All except `" & ActiveSheet.Name & "` hidden."

    SheetVisibility True 'Unhide all sheets.

End Sub

Sub SheetVisibility(Optional ShowAll As Boolean = False)

    Dim wrkSht As Worksheet

    For Each wrkSht In ThisWorkbook.Worksheets
        If wrkSht.Name <> ActiveSheet.Name Then
            wrkSht.Visible = IIf(ShowAll, xlSheetVisible, xlSheetHidden)
        End If
    Next wrkSht

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM