由于我是Vba的全新用户,因此我正在寻求帮助,以编写有关根据单元格的值在Excel中隐藏或取消隐藏工作表的代码 到目前为止,我已经达到了
Sub Hide_Un()
If Range("b4").Value = "yes" Then
sheets(2).Visible = True
ElseIf Range("b4").Value = "no" Then
sheets(2).Visible = False
End If
If Range("b5").Value = "yes" Then
sheets(3).Visible = True
ElseIf Range("b5").Value = "no" Then
sheets(3).Visible = False
End If
但是工作表大约有100张,每次添加新工作表时我都无法执行此过程。因此,我需要一个代码来隐藏或取消隐藏每个工作表,这取决于我对单元格的声明(例如B1 =“ yes”(可见)或b1 =“ no”(不可见)
答案 0 :(得分:2)
Option Compare Text
使此名称不区分大小写。这样YES
= yes
。没有此选项,它们将不相等yes
也不是no
的选项。如果值是y
或n
或yes
并带有滞后空格怎么办? Sheet(n)
)可能会出现问题。Sheet # = Row -2
的工作表号有关。我从4开始循环。最低可能是3-否则,您最终将试图隐藏可能不存在的工作表Option Explicit
Option Compare Text
Sub Hide_Un()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("TOC")
Dim i
Application.ScreenUpdating = False
For i = 4 To ws.Range("B" & ws.Rows.Count).End(xlUp).Row
If ws.Range("B" & i) = "yes" Then
ThisWorkbook.Sheets(i - 2).Visible = xlSheetVisible
ElseIf ws.Range("B" & i) = "no" Then
ThisWorkbook.Sheets(i - 2).Visible = xlSheetHidden
Else 'What if the cell is neither?
'Do what you want if the cell is not "yes" or "no"
End If
Next i
Application.ScreenUpdating = True
End Sub
答案 1 :(得分:2)
将此代码放入ThisWorkbook代码表中。
Option Explicit
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Select Case LCase(Sh.Name)
Case "toc"
If Not Intersect(Target, Sh.Range("B:B")) Is Nothing Then
Dim t As Range
For Each t In Intersect(Target, Sh.Range("B:B"))
If t.Row > 3 Then
Worksheets(t.Row - 2).Visible = _
CBool(LCase(t.Value) = "yes")
End If
Next t
End If
Case Else
'do nothing
End Select
End Sub