我目前有一个循环,可以很好地隐藏基于多个下拉单元格的列。我还想添加代码来隐藏基于相同下拉列表的表单,但我不确定如何添加到我的For Each Cell In Range以适应这种情况。我已经粘贴了我隐藏下面列的内容。任何帮助将不胜感激。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
For Each cell In Range("$A$30:$A$38")
If cell = "Descriptor 1" Or cell = "Descriptor 2" Then
Columns("B:F").EntireColumn.Hidden = False
Exit For
Else
Columns("B:F").EntireColumn.Hidden = True
End If
Next Cell
答案 0 :(得分:1)
您可以使用Worksheets("sheet_to_hide").Visible = xlSheetHidden
之类的内容隐藏工作表,并使用Worksheets("sheet_to_unhide").Visible = xlSheetVisible
取消隐藏工作表。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
Dim HideIt As Boolean
HideIt = True
For Each cell In Range("$A$30:$A$38")
If cell.Value = "Descriptor 1" Or _
cell.Value = "Descriptor 2" Then
HideIt = False
Exit For
End If
Next Cell
If HideIt Then
Columns("B:F").Hidden = True
Worksheets("Sheet1").Visible = xlSheetHidden
Worksheets("Sheet2").Visible = xlSheetHidden
Else
Columns("B:F").Hidden = False
Worksheets("Sheet1").Visible = xlSheetVisible
Worksheets("Sheet2").Visible = xlSheetVisible
End If
End Sub
如果工作表要隐藏/可见,取决于他们的工作表名称是否出现在您的范围内,那么我建议进行以下修改:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
Dim HideIt As Boolean
'Don't do anything if there was no change to A30:A38
If Intersect(Target, Range("$A$30:$A$38")) Is Nothing Then Exit Sub
HideIt = True
For Each cell In Range("$A$30:$A$38")
If cell.Value = "Descriptor 1" Or _
cell.Value = "Descriptor 2" Then
HideIt = False
Exit For
End If
Next cell
Columns("B:F").Hidden = HideIt
Dim ws As Worksheet
For Each ws In Worksheets
If ws.Name <> ActiveSheet.Name Then
'See if sheet name exists in A30:A38
'Hide the sheet if doesn't, make it visible if it does
ws.Visible = Not IsError(Application.Match(ws.Name, Range("$A$30:$A$38"), 0))
End If
Next
End Sub
答案 1 :(得分:0)
@ YowE3K你的代码很棒。但我有一个问题,标签名称是简短的形式,我的描述符是完整的形式。所以,我拿了原始代码,为每个标签添加了一个“HideTab”,并将顶线HideTab = False切换为true,并在第4行HideTab中反转它(见下文)。我确信有更快的方式,但这就像一个魅力。非常感谢您的帮助!你指出了我正确的方向。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
Dim HideIt As Boolean
HideIt = True
For Each cell In Range("$A$30:$A$38")
If cell.Value = "Descriptor 1" Or
cell.Value = "Descriptor 2" Then
HideIt = False
Exit For
End If
Next Cell
Columns("B:F").EntireColumn.Hidden = True
Dim HideTab1 As Boolean
HideTab1 = False
For Each cell In Range("$A$30:$A$38")
If cell = "Descriptor1" Then
HideTab1 = True
Exit For
End If
Next cell
Sheets("Desc1").Visible = HideTab1
Dim HideTab2 As Boolean
HideTab2 = False
For Each cell In Range("$A$30:$A$38")
If cell = "Descriptor2" Then
HideTab2 = True
Exit For
End If
Next cell
Sheets("Desc2").Visible = HideTab2
Dim HideTab3 As Boolean
HideTab3 = False
For Each cell In Range("$A$30:$A$38")
If cell = "Descriptor3" Then
HideTab3 = True
Exit For
End If
Next cell
Sheets("Desc3").Visible = HideTab3
End Sub