Excel VBA编程 典型实例——读取ACCESS数据

Excel VBA编程 典型实例——读取ACCESS数据


2024年1月20日发(作者:)

Excel VBA编程 典型实例——读取ACCESS数据

利用VBA,不仅可以对文本文件进行操作,还可以对Office其他组件进行操作。例如,通过ADO读取ACCESS中的数据,这样使得Excel更加灵活。

1.练习要点

 使用ADO连接

 查询数据库数据

2.操作步骤

(1)启动Excel 2007,并打开VBE窗口,新建一个用户窗体,设置其Caption为“人员信息查询”。

(2)在该窗体中,添加一个多页控件,设置其中一个页为“查找”,并在该页中添加如图18-8所示的控件。

添加控件

图18-8 添加控件

(3)设置另一个页为“资料”,并添加如图18-9所示的控件。

设置“资料”页

图18-9 设置“资料”页

(4)在页控件下面添加一个命令按钮,并设置其Caption属性为“关闭”,如图18-10所示。

添加

图18-10 添加按钮

(5)打开该窗体的【代码】窗口,在窗体的Initialize事件代码。

'声明ADO连接对象

Dim cnn As tion

'声明ADO命令对象

Dim cmd As d

Private Sub UserForm_Initialize()

Dim strCon As String

'为复合框添加数据

m "身份证号码"

m "姓名"

m "出生日期"

m "单位名称"

dex = 0

'设置列表框为3列

Count = 3

'设置列表框各列的宽度

Widths = "20;100;60"

'新建连接对象

Set cnn = New tion

'定义连接字符串

strCon = "Provider=.4.0;Data Source=" & _

& "数据库.mdb"

'设置连接参数

tionString = strCon

'新建命令对象

Set cmd = New d

'打开“查找”页

= 0

End Sub

(6)设置“查找”按钮的Click事件。

Private Sub cmdFind_Click()

'声明保存SQL语句

Dim strSql As String

Dim rs As set

'说明数组

Dim aRs(100, 3) As String

Dim i As Integer

If = "" Then

MsgBox "请输入查询关键字"

us

Exit Sub

End If

'根据不同字段生成查询

Select Case

Case "身份证号码"

strSql = "Select * From 人员信息 Where Identifcard_id Like '%" &

& "%'"

Case "姓名"

strSql = "Select * From 人员信息 Where Member_Name Like '%" &

& "%'"

Case "出生日期"

'判断日期格式是否正确

If IsDate() Then

strSql = "Select * From 人员信息 Where Birthday=#" & &

"#"

Else

MsgBox "请输入正确的日期格式!"

us

Exit Sub

End If

Case "单位名称"

strSql = "Select fcard_id,_Name,_name " & _

" From 人员信息 AS a, 工作单位 AS b " & _

" Where _id=_id AND _name Like '%" & &

"%'"

End Select

'打开ADO连接

'设置命令对象的连接属性

Connection = cnn

'设置命令对象执行的SQL语句

dText = strSql

'执行SQL语句,将结果保存在记录集中

Set rs = e()

i = 0

'循环处理记录集

Do While Not

aRs(i, 0) = ("ID").Value

aRs(i, 1) = ("Identifcard_id").Value

aRs(i, 2) = ("Member_Name").Value

i = i + 1

xt

Loop

'清除列表框中的数据

'列表框赋值

() = aRs

End Sub

(7)设置列表框的Click事件。

Private Sub lstInfo_Click()

Dim i As Integer

Dim strSql As String

Dim rs As set

If = "" Then Exit Sub

'获取列表框第一列的值

i = CInt()

'生成SQL语句

strSql = "Select fcard_id,_Name,,ay,_name " &

_

" From 人员信息 AS a, 工作单位 AS b" & _

" Where _id=_id AND =" & i

Connection = cnn

dText = strSql

Set rs = e()

'获取数据

If Not Then

= ("Member_Name").Value

= ("Identifcard_id").Value

= ("Birthday").Value

= ("unit_name").Value

If ("Sex").Value = 1 Then

= True

Else

= True

End If

End If

End Sub

(8)设置“关闭”按钮的Click事件。

Private Sub cmdExit_Click()

'关闭窗体

Unload Me

End Sub

(9)输入代码后,在“查找”页中的“查找字段”中选择要查找的类型,在“关键字”文字框中输入需要查找的内容,然后单击“查找”按钮,所查询的结果将显示在列表框中。单击列表框中的内容,在“资料”页中将显示所查询的内容。


发布者:admin,转转请注明出处:http://www.yc00.com/news/1705750865a1420734.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信