首页 > 解决方案 > VBA hide and show sheets based on YES/NO and worksheet name

问题描述

I have a workbook with many sheets. I have an index worksheet that list the names of the worksheets in column B and a Yes/No question in column c. I want a code that when I click "YES" it will open the worksheet that it corresponds to. When I click "NO" it will hide the worksheet. The names in the list exactly match the name of the worksheets. I presume it will be with a loop?

Range is from B27 to C61

标签: vbaloopshideshow

解决方案


If we assume column 2 contains the name of the sheet and column 3 contains either Yes or No, then this code will do it, using double-click:

Option Explicit

Private Function GetSheet(SheetName As String) As Worksheet
    On Error Resume Next
    Set GetSheet = ThisWorkbook.Sheets(SheetName)
    If Err.Number <> 0 Then
        Err.Clear
    End If
End Function

Private Sub ShowHideClick(Rng As Range, ActivateSheet As Boolean)
    Dim RowNum As Long, ColNum As Long
    Dim YesNo As String
    Dim SheetName As String
    Dim Sht As Worksheet
    
    RowNum = Rng.Row
    ColNum = Rng.Column
    If Not (RowNum >= 27 And RowNum <= 61 And ColNum = 3) Then Exit Sub
    YesNo = Rng
    If YesNo <> "Yes" And YesNo <> "No" Then Exit Sub
    SheetName = Rng.Offset(0, -1)
    Set Sht = GetSheet(SheetName)
    If Sht Is Nothing Then Exit Sub
    If YesNo = "Yes" Then
        If Sht.Visible = xlSheetVeryHidden Then
            Sht.Visible = xlSheetHidden
        End If
        Sht.Visible = xlSheetVisible
        If ActivateSheet Then
            Sht.Activate
        End If
        Rng.Value = "No"
    Else
        If Sht.Visible = xlSheetVisible Then
            Sht.Visible = xlSheetHidden
        End If
        Rng.Value = "Yes"
    End If
End Sub

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Cancel = True
    ShowHideClick Target, True
End Sub

Insert the code in the woorksheet containing the Yes/No table.


推荐阅读