excelvbacommandbutton

Command button in excel to open hidden tab and jump to that tab


I am not very experienced with VBA and hoping the community can help me with a challenge I am facing. I have an excel workbook with about 20 tabs. I am trying to accomplish the following:

  1. When the user opens the workbook, only one main tab appears. This works for me using the following (only 3 sheets in this example)
    Private Sub Workbook_Open()
      Sheet1.Visible = xlSheetVisible
      Sheet2.Visible = xlSheetHidden
      Sheet3.Visible = xlSheetHidden
    End Sub
  1. There will be command buttons for each of the hidden tabs. The user will select the command button of their choosing, excel will unhide that tab and the workbook will automatically jump to that tab ("test_tab" in this example). I have the code below that opens the unhidden tab, but I stay on the main tab that holds all of the command buttons. I would like the command button to take the user to "test_tab" upon clicking the command button.
    Private Sub CommandButton1_Click()
      ThisWorkBook.Worksheets ("test_tab").Visible = xlSheetVisible
    End Sub

I've done a lot of research, watched tutorials but none seem to have this exact use case. Hoping someone can help me out.


Solution

  • You need to add a line to activate the worksheet.

    Private Sub CommandButton1_Click()
       ThisWorkBook.Worksheets ("test_tab").Visible = xlSheetVisible
       ThisWorkBook.Worksheets ("test_tab").Activate
    End Sub