如何用密码保护和隐藏除两个工作表以外的所有工作表?

时间:2018-07-14 00:38:46

标签: excel vba excel-vba password-protection

我在this forum中遇到了以下VBA功能,该功能可用于保护一张纸的密码,但是我想用密码保护除两张纸以外的所有纸:

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim MySheets As String, Response As String
MySheet = "Sheet1"
If ActiveSheet.Name = MySheet Then
ActiveSheet.Visible = False
    Response = InputBox("Enter password to view sheet")
        If Response = "MyPass" Then
            Sheets(MySheet).Visible = True
            Application.EnableEvents = False
            Sheets(MySheet).Select
            Application.EnableEvents = True
        End If
End If
Sheets(MySheet).Visible = True
End Sub

我的工作簿中有五个工作表(“工作表1”,“工作表2”,“工作表3”,“工作表4”,“工作表5”),我希望除工作表1和工作表2之外的所有工作表都受密码保护和隐藏。换句话说,Sheet3,Sheet4和Sheet5都应使用上述代码进行密码保护

我将功能更新如下,但即使输入正确的密码后,它甚至不显示任何其他表格

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim MySheets As String, Response As String
MySheet = "Sheet1"
MySheet2 = "Sheet2"
If ActiveSheet.Name <> MySheet And ActiveSheet.Name <> MySheet2 Then
   ActiveSheet.Visible = False
    Response = InputBox("Enter password to view sheet")
        If Response = "MyPass" Then
            Sheets(MySheet).Visible = True
            Application.EnableEvents = False
            Sheets(MySheet).Select
            Application.EnableEvents = True
        End If
End If
Sheets(MySheet).Visible = True
Sheets(MySheet2).Visible = True

End Sub

2 个答案:

答案 0 :(得分:0)

您没有使用Workbook_SheetActivate给您的礼物。 Sh 是正在被激活的工作表对象。

您的变量声明很重要;您将Dim MySheets声明为String,但从不使用它,并在未声明它们的情况下将MySheet =“ Sheet1”和MySheet2 =“ Sheet2”分配。

工作表的codename property可以更好地处理某些级别的工作表标识,而更改频率要低得多。

Option Explicit

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
    Dim response As String

    If IsError(Application.Match(Sh.CodeName, Array("Sheet1", "Sheet2"), 0)) Then
        Sh.Visible = xlSheetHidden

        response = InputBox("Enter password to view sheet")
        If response = "MyPass" Then
            Application.EnableEvents = False
            Sh.Visible = xlSheetVisible
            Sh.Activate
            Application.EnableEvents = True
        End If
    End If

    Sheet1.Visible = True
    Sheet2.Visible = True

End Sub

Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)

    If IsError(Application.Match(Sh.CodeName, Array("Sheet1", "Sheet2"), 0)) Then
        Sh.Visible = xlSheetHidden
    End If

End Sub

答案 1 :(得分:0)

另一个选择是绑定到“命名范围”。您可以使用工作表范围创建命名范围,例如: Name manager Ctrl+F3

然后创建其他函数,以检查该名称是否存在并获取其值。根据结果​​,工作表是否被隐藏。

matrix <- as.matrix(df_agg)

这是隐藏工作表的代码(您可以在此处轻松添加保护工作表的代码等):

Public Function bIsVisible(ByRef wksSheet As Worksheet) As Boolean
    Dim bResult     As Boolean

    bResult = False
    On Error Resume Next
    bResult = Evaluate(wksSheet.Names("Visible").Value)

    bIsVisible = bResult
End Function