数据窗口中的ole控件 pb_工作表数据与UserForm窗口的交互过程中如何实现数据的精确查找...
大家好,我们今天继续讲解VBA数据库解决方案,今日讲解的是第82讲:工作表数据与UserForm窗口的交互中:如何实现数据的查找。在讲窗体和数据库的交互对接中,我先后讲解实现了数据的首个记录的显示,下一条记录的显示,最后记录的显示,数据的录入,编辑,保存等功能,今日讲数据的精确查询,也就是说在录入一个唯一值后,把这个唯一值的匹配显示在窗体中。
思路,①在UserForm窗口上,设置查找按钮,用于指令的下达。
②在弹出UserForm窗口后,EXCEL文件要隐藏。
③要考虑到按钮之间的作用,在弹出对话框后只能显示查找、退出按钮。
下面我们首先实现UserForm窗体:在上一讲的基础上我这次增加的是“查找”按钮:
下面看我的代码:
1 从EXCEL窗口进入人机交互窗口:
Sub mynzRecords_82() '将工作表数据变成记录集,并实现利用UserForm窗口进行查找数据
Application.Visible = False
UserForm1.Show
End Sub
代码解释:上述代码完成从EXCEL界面到人机交互UserForm窗体,这时的Application.Caller是7.
2 “查找”按钮响应的代码:
Private Sub CommandButton7_Click() '查找,显示
UserForm1.TextBox2.Value = ""
UserForm1.TextBox2.Value = ""
UserForm1.TextBox3.Value = ""
MsgBox ("请录入员工编号,然后按下回车键!")
UserForm1.TextBox1.SetFocus
End Sub
3 回车键响应的代码:
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
If UserForm1.TextBox1.Value = "" Then MsgBox "员工编号不能为空": Exit Sub
Dim cnADO, rsADO As Object
Dim strPath, strSQL As String
Dim myData() As Variant
Set cnADO = CreateObject("ADODB.Connection")
Set rsADO = CreateObject("ADODB.Recordset")
strPath = ThisWorkbook.FullName
cnADO.Open "provider=Microsoft.ACE.OLEDB.12.0;extended properties='excel 12.0;hdr=yes;imex=1';" _
& "data source=" & strPath
strSQL = "SELECT * FROM [数据7$] where 员工编号=" & UserForm1.TextBox1.Value
rsADO.Open strSQL, cnADO, 1, 3
If rsADO.RecordCount > 0 Then
UserForm1.TextBox2.Value = rsADO.Fields(1)
UserForm1.TextBox3.Value = rsADO.Fields(2)
UserForm1.TextBox1.SetFocus
Else
MsgBox ("您录入的记录不存在")
End If
rsADO.Close
cnADO.Close
Set rsADO = Nothing
Set cnADO = Nothing
End If
End Sub
代码解释:
当按下的不是回车键时Exit Sub,当是回车键时打开数据库,这里用WHERE预计实现了员工编号的精确查找,找到后显示rsADO.Fields(1)和rsADO.Fields(2)字段的值
4 为了实现按钮的控制在窗体激活后有如下代码
If Right(Application.Caller, 1) = 7 Then '查找
UserForm1.CommandButton3.Enabled = False '开始
UserForm1.CommandButton1.Enabled = False '下一条记录
UserForm1.CommandButton4.Enabled = False '最后一条记录
UserForm1.CommandButton5.Enabled = False '编辑记录
'UserForm1.CommandButton7.Enabled = False '查找记录
UserForm1.CommandButton8.Enabled = False '删除记录
UserForm1.CommandButton6.Enabled = False '保存记录
UserForm1.CommandButton9.Enabled = False '录入记录
UserForm1.TextBox2.Enabled = False
UserForm1.TextBox3.Enabled = False
End If
最后我们看代码的运行:
今日内容回向:
1 实现精确查找的思路是什么样的?
2 本讲代码中,判断要求实现精确查找传递下来的值是什么?
分享成果,随喜正能量