使用VBA编写的一下小的实用程序或小型数据库,有时为了保密或限制某些用户的权限,需要设置登录窗口,不同的用户使用不同的用户名和密码登录,获得不同的权限。 方法及过程如下: 第一步:进入VB编辑器,插入一个用户窗体,以下是我设计的一个下数据库的登录窗体: 其中, User name对应的文本框是textbox1, Password对应的文本框是textbox2。 第二步:代码编写 1.文档打开时,应实现文档隐藏,登录窗出现功能,在Thisworkbook中写入如下代码: Private Sub Workbook_Open() Application.Visible = False UserForm1.Show End Sub 2.用户窗体中的程序,以我做的一个小数据库为例,我设置了三种权限:数据库只读权限,数据库输入权限,管理员权限。 如果用户在登录窗口点击关闭按钮(是不是指的是叉?),则文档应该被关闭掉,所以在用户窗体中写入以下代码: Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) Application.Visible = True ThisWorkbook.Close End Sub 登录窗体中验证用户名和密码是否正确的程序: Private Sub CommandButton1_Click() '点击OK按钮时 If TextBox1.Text = Sheet5.Cells(2, 2).Value And TextBox2.Text = Sheet5.Cells(2, 3).Value Then adminunhide ’管理员权限登录时,所有表格都可见 reportunhide dataunhide inputunhide Application.Visible = True For i = 1 To Sheets.Count Sheets(i).Visible = True Next ElseIf TextBox1.Text = Sheet5.Cells(3, 2).Value And TextBox2.Text = Sheet5.Cells(3, 3).Value Then dataunhide '以只读权限进入时,只有数据可以读取 Application.Visible = True For i = 1 To Sheets.Count Sheets(i).Visible = True Next Sheet1.Protect Password:=123, DrawingObjects:=True, Contents:=True, Scenarios:=True Sheet3.Protect Password:=123, DrawingObjects:=True, Contents:=True, Scenarios:=True _ , AllowSorting:=True, AllowFiltering:=True Sheet3.EnableSelection = xlNoRestrictions ElseIf TextBox1.Text = Sheet5.Cells(4, 2).Value And TextBox2.Text = Sheet5.Cells(4, 3).Value Then dataunhide ’以数据输入者权限进入时,只能使用输入界面和数据存储表 inputunhide Application.Visible = True For i = 1 To Sheets.Count Sheets(i).Visible = True Next Sheet1.Protect Password:=123, DrawingObjects:=True, Contents:=True, Scenarios:=True Sheet3.Unprotect Password:=123 Else '输入的用户名或密码错误时 MsgBox "User name or password error,access denied." TextBox2.Text = "" TextBox2.SetFocus Exit Sub End If UserForm1.Hide End Sub 说明:各种权限的用户名和密码存储在Excel的一张表中,这张表只有以管理员权限登录时才能被看见。程序登录时会比较输入的用户名密码和表中存储的用户名密码是否一致。 |
|
来自: lwc5577 > 《电脑应用-EXCEL应用》