“ 连接数据库,并将筛选后的语句写入建立的窗体中,便于查阅”
01
—
窗体样式
02
—
代码实例
Option Explicit '打开强制声明Dim con As ADODB.Connection '声明连接对象变量Dim rs As ADODB.Recordset '声明记录集对象变量'一、窗体加载事件,加载去重后的部门名称Private Sub UserForm_Initialize() '1.建立数据库连接 Set con = New ADODB.Connection With con .Provider = "microsoft.ace.oledb.12.0" .ConnectionString = "C:\Users\cgdwemin.ASIA.000\Desktop\学生管理.accdb" .Open End With '2.提取不重复的部门名称 Dim Access_Sql As String, i As Integer Access_Sql = "select distinct 部门 from 员工" Set rs = New ADODB.Recordset '创建记录集对象 rs.Open Access_Sql, con, adOpenKeyset, adLockOptimistic '3.将记录集中的部门名称显示到List_Dept列表框中 With List_Dept .Clear '清空表格内容 For i = 1 To rs.RecordCount .AddItem rs("部门") rs.MoveNext '将记录集中的指针指向下一条记录 Next End With rs.Close '取消占用End Sub'二、鼠标选择某个部门相当于单击列表框,即单击列表框,查询所选的部门的员工(提取员工的编号和姓名,避免姓名重复的问题)Private Sub List_Dept_Click() '1.编写查询语句,查询出不重复的部门编号 Dim Access_Sql As String, i As Integer Access_Sql = "select 编号, 姓名 from 员工 where 部门 = '" & List_Dept.Value & "' order by 编号" rs.Open Access_Sql, con, adOpenKeyset, adLockOptimistic '2.将查询出的内容通过循环语句依次写入列表中 With List_Employee .Clear '清空列表内容 For i = 1 To rs.RecordCount '查询的个数 .AddItem rs("编号") & Space(2) & rs("姓名") rs.MoveNext '将记录集中的指针指向下一条记录 Next End With rs.CloseEnd Sub'三、单击列表框,查询所选的部门的员工的信息并填入员工信息表中Private Sub List_Employee_Click() '1.按照控件名称和数据库的顺序,构建数组,便于后续将查询的结果写入 Dim arr Dim i As Integer arr = Array("Text_No", "Text_Name", "Text_IDcard", "Text_Dept", "Text_Age", "Text_Post", "Text_Date", "Text_Site", _ "Text_email", "Text_brief") '2.编写查询语句并查询指定内容 Dim Access_Sql As String Access_Sql = "select * from 员工 where 编号=" & Left(List_Employee.Value, 1) rs.Open Access_Sql, con, adOpenKeyset, adLockOptimistic '3.用循环将员工信息写入对应的控件中 For i = 0 To UBound(arr) Me.Controls(arr(i)).Value = rs.Fields(i) 'Me指的是代码所在窗体,Controls指的是控件集(后面为索引),Fields指的是数据库字段(后面为索引) Next rs.CloseEnd Sub'四、释放变量空间,关闭数据库连接,关闭窗体Private Sub CommandButton1_Click() con.Close Set rs = Nothing Set con = Nothing Unload MeEnd Sub