【发布时间】:2016-12-18 18:47:24
【问题描述】:
我需要在 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
每当我单击其他工作表然后单击返回 sheet1 时都会出现此问题,它要求输入密码(因为
`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(index) 因为对于某些工作表名称错误 9 会导致问题:)))
【问题讨论】:
-
为什么不使用开始页面上的按钮来触发密码请求?使用 Sheet_Activate 事件似乎不是正确的方法。
-
(只是要指出,因为我不确定您使用密码的最终目标是什么,但如果用户真的想要,Excel 中的密码可以是pretty easily bypassed。它可能是如果您的用户是新用户/对 Excel 不太了解,那很好,但如果有人想进入那里,他们可能可以。)另外,我可能遗漏了一些东西,从技术上讲,您不是在添加密码,您只是在制作工作表根据用户输入的字符串可见或不可见。