简体   繁体   English

根据范围内单元格的值隐藏Excel工作表

[英]Hide Excel sheet based on value of a cell in a range

I'm trying to hide a sheet in an Excel workbook based on the contents of any of the cells in a given range. 我试图根据给定范围内任何单元格的内容在Excel工作簿中隐藏工作表。

Let's say I have two sheets - "Sheet1" and "Sheet2". 假设我有两张纸:“ Sheet1”和“ Sheet2”。
On Sheet1, I want to set up a range - cell C10 to F10. 在Sheet1上,我要设置一个范围-单元格C10至F10。
Each of these cells can either be blank, or contain "Yes" or "No" - chosen from a dropdown box. 这些单元格中的每个单元格都可以为空白,也可以包含“是”或“否”(从下拉框中选择)。
If ANY of the cells in the range are set to "Yes", I want Sheet2 to be visible, otherwise (if all the cells are either blank or contain "No") I want Sheet2 hidden. 如果该范围内的任何单元格都设置为“是”,则我希望Sheet2可见,否则(如果所有单元格均为空白或包含“否”),我希望隐藏Sheet2。

I've tried various pieces of code, including the below. 我尝试了各种代码,包括下面的代码。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rCell As Range

    Application.ScreenUpdating = False
    For Each rCell In Range("C10:F10")
        If rCell.Value = "Yes" Then
            Worksheets("Sheet2").Visible = True
        Else
            Worksheets("Sheet2").Visible = False
        End If
    Next rCell
    Application.ScreenUpdating = True
End Sub

I've got about as far as Sheet 2 being visible if all the cells equal "Yes" or if F10 equals "Yes", but not if only one of the cells contains "Yes". 如果所有单元格都等于“ Yes”或F10等于“ Yes”,那么工作表2可见,但是如果只有一个单元格包含“ Yes”,则不是。

No loop needed, and create an If to test whether the Cell that change is in the range to test, just to save some comp time: 无需循环,并创建一个If来测试更改的单元格是否在要测试的范围内,只是为了节省一些计算时间:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Range("C10:F10"),Target) Is Nothing Then
        Worksheets("Sheet2").Visible = Application.Countif(Range("C10:F10"),"Yes")>0
    End If
End Sub

Modify and try: 修改并尝试:

Option Explicit

Sub test()

    Dim ws As Worksheet
    Dim rng As Range, cell As Range
    Dim Hide As Boolean

    For Each ws In ThisWorkbook.Worksheets

        Set rng = ws.Range("C10:F10")

        For Each cell In rng
            Hide = False
            If cell.Value = "Yes" Then
                Hide = False
                Exit For
            Else
                Hide = True
            End If
        Next

        If Hide = True Then
            ws.Visible = False
        End If

    Next

End Sub

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

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