VBA 根据 YES/NO 和工作表名称隐藏和显示工作表
VBA hide and show sheets based on YES/NO and worksheet name
我有一个包含很多工作表的工作簿。我有一个索引工作表,它在 B 列中列出了工作表的名称,在 c 列中列出了一个 Yes/No 问题。我想要一个代码,当我单击“是”时,它将打开它对应的工作表。当我单击“否”时,它将隐藏工作表。列表中的名称与工作表的名称完全匹配。我猜它会有一个循环?
范围从 B27 到 C61
如果我们假设第 2 列包含 sheet 的名称,而第 3 列包含是或否,则此代码将执行此操作,只需双击:
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
在包含 Yes/No table 的工作sheet 中插入代码。
我有一个包含很多工作表的工作簿。我有一个索引工作表,它在 B 列中列出了工作表的名称,在 c 列中列出了一个 Yes/No 问题。我想要一个代码,当我单击“是”时,它将打开它对应的工作表。当我单击“否”时,它将隐藏工作表。列表中的名称与工作表的名称完全匹配。我猜它会有一个循环?
范围从 B27 到 C61
如果我们假设第 2 列包含 sheet 的名称,而第 3 列包含是或否,则此代码将执行此操作,只需双击:
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
在包含 Yes/No table 的工作sheet 中插入代码。