使用宏隐藏选项卡

时间:2016-03-01 17:28:08

标签: excel vba excel-vba

我有一个工作簿,并希望,一旦用户从下拉列表中选择了一个选项,就可以隐藏其他几个工作表。代码目前是 -

Sub select_role()

Dim role As String

role = Sheet3.Cells(11, "F").Value

Select Case role
Case "Project Manager"
Sheet10.Visible = xlSheetHidden
Sheet11.Visible = xlSheetHidden
Sheet4.Visible = xlSheetHidden
Sheet6.Visible = xlSheetHidden
Sheet7.Visible = xlSheetHidden
Sheet8.Visible = xlSheetHidden

Case "Business Analyst"
Sheet10.Visible = xlSheetHidden
Sheet11.Visible = xlSheetHidden
Sheet5.Visible = xlSheetHidden
Sheet6.Visible = xlSheetHidden
Sheet7.Visible = xlSheetHidden
Sheet8.Visible = xlSheetHidden

Case "Developer"
Sheet10.Visible = xlSheetHidden
Sheet11.Visible = xlSheetHidden
Sheet4.Visible = xlSheetHidden
Sheet6.Visible = xlSheetHidden
Sheet5.Visible = xlSheetHidden
Sheet8.Visible = xlSheetHidden

Case "Architect"
Sheet10.Visible = xlSheetHidden
Sheet11.Visible = xlSheetHidden
Sheet4.Visible = xlSheetHidden
Sheet6.Visible = xlSheetHidden
Sheet7.Visible = xlSheetHidden
Sheet5.Visible = xlSheetHidden

Case "Payments"
Sheet5.Visible = xlSheetHidden
Sheet11.Visible = xlSheetHidden
Sheet4.Visible = xlSheetHidden
Sheet6.Visible = xlSheetHidden
Sheet7.Visible = xlSheetHidden
Sheet8.Visible = xlSheetHidden

Case "New Role"
Sheet10.Visible = xlSheetHidden
Sheet5.Visible = xlSheetHidden
Sheet4.Visible = xlSheetHidden
Sheet6.Visible = xlSheetHidden
Sheet7.Visible = xlSheetHidden
Sheet8.Visible = xlSheetHidden

End Select

End Sub

然而,当我调试它时,它正确地进入其中一个案例,然后当它从第一个工作表移动到列表中的第二个时,我得到一个运行时错误' 1004'。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我鼓励你使用这种模式。它更容易维护,更简洁:

Sub Select_Role()
    Dim role As String, shts(), sht As Integer

    role = Worksheets("Sheet3").Range("F11")

    Select Case role
        Case "Project Manager"
            shts = Array(10, 11, 4, 6, 7, 8)
        Case "Business Analyst"
            shts = Array(10, 11, 5, 6, 7, 8)
        Case "Developer"
            shts = Array(10, 11, 4, 6, 5, 8)
        Case "Architect"
            shts = Array(10, 11, 4, 6)
        Case "New Role"
            shts = Array(10, 5, 4, 6, 7, 8)
    End Select

    For sht = 0 To UBound(shts)
        If Worksheets("Sheet" & shts(sht)).Visible Then
            Worksheets("Sheet" & shts(sht)).Visible = xlSheetHidden
        End If
    Next sht

End Sub
  • 每个Array包含您要隐藏的工作表引用。它们可以是工作表名称或索引。
  • 您可以轻松更新每个阵列以满足您的需求,以及添加和删除新案例
  • 循环首先检查工作表是否可见,但您可以添加更多条件,例如protectedxlVeryHidden等......