基于列表隐藏工作表

时间:2015-01-08 17:33:19

标签: excel vba excel-vba

嘿有一个简单的问题我正在编写一个代码,根据工作表名称旁边的字段是“是”还是“否”来隐藏工作表列表。因此,我有29个工作表的列表,我希望我的代码查看该名称旁边的字段,如果是,则显示它,如果不是它将隐藏它。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim ws As Worksheet

    For Each ws In Worksheets
        If ws.Name = Worksheets("Settings").Range("B4:B32") _
        And Worksheets("Setting").Range("C4:C32") = "Yes" Then
            ws.Visible = True
        End If
        If ws.Name = Worksheets("Settings").Range("B4:B32") _
        And Worksheets("Setting").Range("C4:C32") = "No" Then
            ws.Visible = True
        End If
    Next ws
End Sub

我运行此操作并不断出现错误错误我是编程新手,因此我不认为我正在正确地调用内容

3 个答案:

答案 0 :(得分:0)

我相信以下代码应该符合您的需求:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim wsSettings As Worksheet
    Dim wsHideShow As Worksheet
    Dim rngSheets As Range
    Dim xlCell As Range
    Dim sheetName As String

    Set wsSettings = ThisWorkbook.Worksheets("Settings")
    Set rngSheets = wsSettings.Range("B4:B32")

    For Each xlCell In rngSheets
        sheetName = xlCell.Value

        If sheetName <> "" Then

            Set wsHideShow = ThisWorkbook.Worksheets(sheetName)

            If xlCell.Offset(0, 1).Value = "yes" Then
                wsHideShow.Visible = False
            Else
                wsHideShow.Visible = True
            End If
        End If
    Next xlCell

End Sub

不是循环浏览工作表,而是遍历列表并相应地隐藏/显示工作表。

答案 1 :(得分:0)

打字速度慢......但......我的建议是:

Private Sub WorkSheet_Change(ByVal Target as range)

   If (Target.Row >= 4 And Target.Row <= 32 And Target.Column = 2) Then
      Dim i as Integer
      For i=0 To 28 Step 1
         If Range("B" & 2 + i).Value = "YES" Then
           ThisWorkBook.Worksheets(Range("A" & 2 + i).Value).Visible = True
         Else
           ThisWorkBook.Worksheets(Range("A" & 2 + i).Value).Visible = False
         End If
      Next i
   End If

End Sub

仅当工作表上B4:B32范围内的值发生变化时才会触发...

希望这会有所帮助......

答案 2 :(得分:0)

此代码在标准模块中运行。它假定主人是设置而不是设置

它遍布桌子和床单:

Sub DisplayOrHideSheets()
    Dim sh As Worksheet
    For Each ws In Sheets
        v = ws.Name
        For Each r In Worksheets("Settings").Range("B4:B32")
            If r.Value = v Then
                If r.Offset(0, 1) = "Yes" Then
                    ws.Visible = True
                Else
                    ws.Visible = False
                End If
            End If
        Next r
    Next ws
End Sub