摘要:' LoginForm代码Private Sub btnLogin_ClickDim user As String, pass As Stringuser = Trim(txtUser.Text)pass = Trim(txtPass.Text)If user
' LoginForm代码Private Sub btnLogin_ClickDim user As String, pass As Stringuser = Trim(txtUser.Text)pass = Trim(txtPass.Text)If user = "" Or pass = "" ThenMsgBox "请输入用户名和密码!", vbExclamationExit SubEnd IfDim permission As Integerpermission = AuthenticateUser(user, pass)If permission > 0 ThenUnload MeApplication.Visible = TrueShowDashboard permission ' 根据权限显示界面ElseMsgBox "无效的用户名或密码!", vbCriticaltxtPass.Text = ""txtPass.SetFocusEnd IfEnd SubPrivate Sub btnCancel_ClickThisWorkbook.Close SaveChanges:=FalseEnd Sub' 标准模块代码Function AuthenticateUser(user As String, pass As String) As IntegerDim ws As WorksheetSet ws = ThisWorkbook.Sheets("UserDB")Dim lastRow As LonglastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).RowFor i = 2 To lastRowIf LCase(ws.Cells(i, 1).Value) = LCase(user) ThenIf ws.Cells(i, 2).Value = pass ThenAuthenticateUser = ws.Cells(i, 3).ValueExit FunctionEnd IfEnd IfNext iAuthenticateUser = 0 ' 验证失败End FunctionSub ShowDashboard(permission As Integer)' 隐藏所有工作表Dim ws As WorksheetFor Each ws In ThisWorkbook.Worksheetsws.Visible = xlSheetVeryHiddenNext' 根据权限显示界面Select Case permissionCase 1 ' 普通用户Sheets("UserDashboard").Visible = xlSheetVisibleApplication.Caption = "普通用户模式"Case 2 ' 管理员Sheets("AdminDashboard").Visible = xlSheetVisibleApplication.Caption = "管理员模式"End Select' 禁用开发者权限Application.ExecuteExcel4Macro "SHOW.TOOLBAR(""Ribbon"",False)"End Sub' 管理员模块代码Sub AddNewUserDim user As String, pass As String, perm As Integeruser = InputBox("输入用户名:")pass = InputBox("输入密码:")perm = InputBox("权限等级 (1-用户, 2-管理员):")If user
"" And pass
"" ThenDim ws As WorksheetSet ws = Sheets("UserDB")Dim newRow As LongnewRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row + 1ws.Cells(newRow, 1).Value = userws.Cells(newRow, 2).Value = passws.Cells(newRow, 3).Value = permMsgBox "用户添加成功!"End IfEnd Sub' ThisWorkbook 代码Private Sub Workbook_OpenApplication.Visible = False ' 隐藏Excel界面LoginForm.Show ' 显示登录窗体' 保护用户数据库Sheets("UserDB").Visible = xlSheetVeryHiddenEnd SubPrivate Sub Workbook_BeforeClose(Cancel As Boolean)' 关闭时恢复设置Application.Visible = TrueApplication.Caption = EmptyApplication.ExecuteExcel4Macro "SHOW.TOOLBAR(""Ribbon"",True)"End Sub加密密码:' 在写入数据库前加密ws.Cells(newRow, 2).Value = Base64Encode(pass)' 验证时解密Function Base64Decode(ByVal strData As String) As String' 添加Base64编解码函数End Function锁定VBA工程:工具 → VBAProject属性 → 保护 → 勾选"查看时锁定工程"保护工作表:Sheets("UserDB").Protect Password:="yourStrongPassword", _UserInterfaceOnly:=True注意事项:
来源:凡妈小厨房
免责声明:本站系转载,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与本站联系,我们将在第一时间删除内容!