How to create a button to hide or show a sheet using VBA?

To create a button that hides or shows a worksheet using VBA in Excel, you will need to follow these steps:

Sub ToggleSheetVisibility()
    Dim ws As Worksheet
    ' Replace Sheet1 with the name of your sheet
    On Error Resume Next
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    On Error GoTo 0
    
    If ws Is Nothing Then
        MsgBox "The specified sheet does not exist."
        Exit Sub
    End If

    If ws.Visible = xlSheetVisible Then
        ws.Visible = xlSheetHidden
    Else
        ws.Visible = xlSheetVisible
    End If
End Sub
  • Open the Excel Workbook:
    • Open the Excel workbook where you want to add the button.
  • Access the Developer Tab:
    • If you don’t have the Developer tab visible, you can enable it by going to `File` -> `Options` -> `Customize Ribbon`, then check the `Developer` checkbox on the right pane.
  • Insert a Button:
    • Go to the Developer tab.
    • Click on `Insert` in the Controls group and select `Button (Form Control)` from the dropdown.
    • Click on the worksheet where you want to place the button, and it will create a button.
  • Assign a Macro to the Button:
    • Right-click on the button and select `Assign Macro`.
    • Click on `New` to create a new macro.
  • Write the VBA Code:
    • You will be in the Visual Basic for Applications (VBA) editor. Enter the following code:
    • Replace `”Sheet1″` with the name of the sheet you wish to hide/show.
    • Close the VBA editor.
  • Finalize the Button:
    • You will be back in Excel. Ensure the button is appropriately sized and positioned.
    • Click on `OK` to assign the `ToggleSheetVisibility` macro to your button.
  • Test the Button:
    • Click the button to hide or show the specified sheet.

This macro will toggle the visibility of the specified sheet each time you click the button. If the sheet is visible, clicking the button will hide it, and vice versa. Adjust the button’s caption to make it clear what functionality it offers to the users.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project