如何在vba中为多个工作表设置密码?

时间:2016-12-18 18:47:24

标签: excel vba excel-vba macros

我需要在vba中为多个excel表设置密码。我有一份excel文档,其中包含不同公司部分的表格。我希望当我打开excel文档时只显示启动页面,然后当我输入密码时,如果它是正确的,那么只打开该部分的两张纸。想法是: 打开excel文档,显示起始页面。 输入6个部分之一的密码 如果section1或section 2 ...或section 4的密码正确,请显示属于我们输入密码的部分的两张表。 如果第5部分或第6部分的密码正确,则显示所有工作表。我已经尝试使用此代码锁定一张表格:

Private Sub Workbook_SheetActivate(ByVal Sh As Object)

    Dim xSheetName As String
    xSheetName = "Sheet1"
    If Application.ActiveSheet.Name = xSheetName Then
       Application.EnableEvents = False
       Application.ActiveSheet.Visible = False
       xTitleId = "KutoolsforExcel"
       response = Application.InputBox("Password", xTitleId, "", Type:=2)
       If response = "123456" Then
          Application.Sheets(xSheetName).Visible = True
          Application.Sheets(xSheetName).Select
       End If
 End If
 Application.Sheets(xSheetName).Visible = True
 Application.EnableEvents = True
 End Sub

每当我点击其他工作表,然后点击返回工作表1时,它就会出现问题请求输入密码(因为

                       `If Application.ActiveSheet.Name = xSheetName Then
                               Application.EnableEvents = False
                               Application.ActiveSheet.Visible = False`

我想,但我不知道如何避免它。 然后,当我试图像这样锁定多张纸时:

Dim xSheetName1 as String
Dim xSheetName3 as String
xSheetName1 = "Sheet1"
xSheetName3 = "Sheet3"
If Application.ActiveSheet.Name = xSheetName1 Then
Application.EnableEvents = False
Application.ActiveSheet.Visible = False
xTitleId = "KutoolsforExcel"
response = Application.InputBox("Password", xTitleId, "", Type:=2)
If response = "123" Then
    Application.Sheets(xSheetName1).Visible = True
    Application.Sheets(2).Visible = True
    Application.Sheets(xSheetName1).Select

If Application.Sheets(1).Visible = True Then

Application.EnableEvents = False
Aplication.Sheets(xSheetName1).Visible = False
Exit Sub
End If
 End If

End If
   If Application.ActiveSheet.Name = xSheetName3 Then
      Application.EnableEvents = False
      Application.ActiveSheet.Visible = False
      xTitleId = "KutoolsforExcel"
     response = Application.InputBox("Password", xTitleId, "", Type:=2)
    If response = "111" Then
      Application.Sheets(xSheetName3).Visible = True
      Application.Sheets(5).Visible = True
      Application.Sheets(5).Select

If Application.Sheets(1).Visible = True Then ' tried to get rid of asking                          

                                               for password every time


    Application.EnableEvents = False
 '  Aplication.Sheets(xSheetName1).Visible = False
  Exit Sub
 End If
 End If
  End If
  Application.Sheets(xSheetName1).Visible = True
  Application.Sheets(xSheetName3).Visible = True
  Application.EnableEvents = True

 End Sub

然后当我输入任何正确的密码时,所有锁定的纸张都会被解锁。 有时我使用了Sheets(索引),因为对于某些工作表名称错误9会产生问题:)))

1 个答案:

答案 0 :(得分:0)

我同意蝙蝠侠,这不是一种非常安全的做法。最好将其作为主文件,并运行宏以使用密码将工作表拆分为多个文件。

这样您仍然可以使用1个文件编辑内容,并仍然可以在1个文件中管理安全性。