我有一个Excel工作簿,其中包含多个工作表。我希望根据主工作表单元格B3:B8中的单元格值隐藏/取消隐藏工作表。主表中的值由用户从预定义列表中更改.
例如:如果"A“存在于"Config”列中,则在我的工作簿中取消隐藏工作表"A“。

目前,我有以下代码,它可以工作,但看起来很笨重,每次在"Config“列中更改值时,Excel都会在代码运行时闪烁:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Integer
Sheets("A").Visible = False
Sheets("B").Visible = False
Sheets("C").Visible = False
Sheets("D").Visible = False
For i = 3 To 8
If InStr(1, Cells(i, 2), "A") Then
Sheets("A").Visible = True
ElseIf InStr(1, Cells(i, 2), "B") Then
Sheets("B").Visible = True
ElseIf InStr(1, Cells(i, 2), "C") Then
Sheets("C").Visible = True
ElseIf InStr(1, Cells(i, 2), "D") Then
Sheets("D").Visible = True
End If
Next i
End Sub我还试图从一个按钮运行这个宏,但是它以第一个真值(工作表变为未隐藏的)结束。
发布于 2019-03-13 13:28:41
我会用这个方法:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Integer
Sheets("A").Visible = xlSheetHidden
Sheets("B").Visible = xlSheetHidden
Sheets("C").Visible = xlSheetHidden
Sheets("D").Visible = xlSheetHidden
Application.ScreenUpdating = False
For i = 3 To 8
If InStr(1, Cells(i, 2), "A") Then Sheets("A").Visible = xlSheetVisible
If InStr(1, Cells(i, 2), "B") Then Sheets("B").Visible = xlSheetVisible
If InStr(1, Cells(i, 2), "C") Then Sheets("C").Visible = xlSheetVisible
If InStr(1, Cells(i, 2), "D") Then Sheets("D").Visible = xlSheetVisible
Next i
Application.ScreenUpdating = True
End Sub发布于 2019-03-13 13:21:22
要帮助优化运行并使其看起来更好,请使用Application.ScreenUpdating。它将减少闪烁,不试图重新绘制scrren直到Sub已经完成运行。如果程序的其余部分没有问题地运行,就应该是您所需要的全部。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Integer
Sheets("A").Visible = False
Sheets("B").Visible = False
Sheets("C").Visible = False
Sheets("D").Visible = False
For i = 3 To 8
If InStr(1, Cells(i, 2), "A") Then
Application.ScreenUpdating = False
Sheets("A").Visible = True
ElseIf InStr(1, Cells(i, 2), "B") Then
Application.ScreenUpdating = False
Sheets("B").Visible = True
ElseIf InStr(1, Cells(i, 2), "C") Then
Application.ScreenUpdating = False
Sheets("C").Visible = True
Application.ScreenUpdating = False
ElseIf InStr(1, Cells(i, 2), "D") Then
Sheets("D").Visible = True
End If
Next i
Application.sScreenUpdating = True
End Sub我也同意他的评论。Ifs会更好。ElseIf假设只有一个条件是正确的,当可能有多个迭代时。
编辑:虽然:它的设置方式,你打算B3:B8之间有"A“的任何值都会显示页面"A”。如果您以不同的方式将其指定为B3 = "A“、B4="B”等,则可以将条件更改为If Target.Address = "$B$3",并使B#成为任何非空值的on/off。
Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
If Target.Address = "$B$3" Then
If IsEmpty(Sheet1.Range("B3")) = False Then
Sheets("A").Visible = True
Else
Sheets("A").Visible = False
End If
End If
''etc etc and so on
Application.ScreenUpdating = True
End Subhttps://stackoverflow.com/questions/55142640
复制相似问题