You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Excel VBA密码验证代码以支持访问多个指定工作表

调整Excel VBA密码访问逻辑,支持单密码解锁多工作表

以下是修改后的完整代码,实现输入对应密码后解锁指定的多个工作表(比如输入EastPassword可同时访问East和East_Dashboard):

Private Sub Workbook_Open()
    Dim pword As String
    On Error GoTo endit
    pword = InputBox("Enter Your Password")
    Select Case pword
      Case Is = "EastPassword": 
          Sheets("East").Visible = True
          Sheets("East_Dashboard").Visible = True
      Case Is = "NorthPassword": 
          ' 可按需添加North对应的多个工作表,示例:
          Sheets("North").Visible = True
          Sheets("North_Dashboard").Visible = True
      Case Is = "WestPassword": 
          ' 同理添加West对应的多个工作表
          Sheets("West").Visible = True
          Sheets("West_Dashboard").Visible = True
      Case Is = "MasterPassword": Call UnHideAllSheets
    End Select
    Sheets("Welcome").Visible = False
    Exit Sub
endit:
    MsgBox "Incorrect Password - contact Name"
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim sht As Worksheet
    Application.ScreenUpdating = False
    Sheets("Welcome").Visible = xlSheetVisible
    For Each sht In ActiveWorkbook.Sheets
        If sht.Name <> "Welcome" Then
            sht.Visible = xlSheetVeryHidden
        End If
    Next sht
    Application.ScreenUpdating = True
End Sub

' 补充完整的管理员解锁所有表的过程(原代码若已有可忽略)
Private Sub UnHideAllSheets()
    Dim sht As Worksheet
    For Each sht In ActiveWorkbook.Sheets
        sht.Visible = xlSheetVisible
    Next sht
End Sub

关键修改说明

  • 在Workbook_Open的Select Case分支中,给每个密码对应的代码块添加了多个工作表的可见性设置,用换行缩进让逻辑更清晰
  • 保留原代码的错误处理逻辑,密码输入错误时仍会弹出提示
  • Workbook_BeforeClose事件逻辑不变,确保关闭工作簿时,除Welcome外所有工作表都被设为xlSheetVeryHidden(这种隐藏方式无法通过Excel界面直接取消,安全性更高)
  • 补充了UnHideAllSheets的完整代码,确保管理员输入MasterPassword时能解锁所有工作表

内容的提问来源于stack exchange,提问作者arcusm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 01:26:02