简体   繁体   English

根据多个单元格值隐藏或取消隐藏工作表

[英]Hide or unhide sheet depending on multiple cell value

For work I'm trying to figure out how I can make a macro in excel to unhide sheets when you type a specific word in a column.对于工作,我试图弄清楚如何在 excel 中创建一个宏,以便在您在一列中键入特定单词时取消隐藏工作表。
I'm totally new to this so it's a big search.我对此完全陌生,所以这是一个很大的搜索。

So far I got this:到目前为止,我得到了这个:

Private Sub Worksheet_Change(ByVal Target As Range)
    If [C2] = "POMP" Then
        Sheets("POMP").Visible = True
    Else
        Sheets("POMP").Visible = False
    End If

    If [C2] = "TANK" Then
        Sheets("TANK").Visible = True
    Else
        Sheets("TANK").Visible = False
    End If

    If [C2] = "VENTILATOR" Then
        Sheets("VENTILATOR").Visible = True
    Else
        Sheets("VENTILATOR").Visible = False
    End If

    If [C2] = "MOTOR" Then
        Sheets("MOTOR").Visible = True
    Else
        Sheets("MOTOR").Visible = False
    End If
End Sub

It's just an example for a much bigger project.这只是一个更大项目的示例。 It works so far.到目前为止它有效。 When I type MOTOR in C2 then the tab of MOTOR unhides.当我在 C2 中键入 MOTOR 时,MOTOR 选项卡将取消隐藏。 Also for the others.也为其他人。 But..但..

It actually has to work for the whole colomn C not only C2.它实际上必须为整个列 C 工作,而不仅仅是 C2。

Could somebody help me with this?有人可以帮我解决这个问题吗?

Also another question.还有另一个问题。 If there have to unhide 2 sheets when you type in a word, how can I put that in the code.如果在输入单词时必须取消隐藏 2 张纸,我该如何将其放入代码中。 Example: I type MOTOR and then the sheets MOTOR and POMP should unhide.示例:我键入 MOTOR,然后应该取消隐藏 MOTOR 和 POMP 表。

If you could help me with this to it would be such a help!如果你能帮我解决这个问题,那将是一个很大的帮助!

Just make a list of your sheet names as array.只需将您的工作表名称列表作为数组。 Loop through that array and check with the WorksheetFunction.Match method if the sheet name exists in column C to hide or show the sheet.遍历该数组并使用WorksheetFunction.Match 方法检查工作表名称是否存在于 C 列中以隐藏或显示工作表。

Note that Application.Match returns an error if the sheet name was not found in column C, so we use this to trigger the hide/show.请注意,如果在 C 列中找不到工作表名称, Application.Match将返回错误,因此我们使用它来触发隐藏/显示。

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim SheetNames() As Variant
    SheetNames = Array("POMP", "TANK", "VENTILATOR", "MOTOR") 'list your sheet names here

    Dim SheetName As Variant
    For Each SheetName In SheetNames
        Dim MatchedRow As Variant
        MatchedRow = Application.Match(SheetName, Me.Columns("C"), 0)

        On Error Resume Next 'catch error if sheet name does not exist
        ThisWorkbook.Worksheets(SheetName).Visible = Not IsError(MatchedRow)
        If Err.Number <> 0 Then MsgBox "Worksheet '" & SheetName & "' not found!", vbCritical
        On Error GoTo 0
    Next SheetName
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM