6.2.3 将数据显示到Excel表格中
时间:2022-06-25 08:58:33
下面利用实例说明如何实现它们的沟通. 有一个名为author的数据表。放入Excel文件中。已知在c盘有一个dbl.mdb文件,数据库里面现在利用VBA实现Excel从db l.mdb文件提取需要的数据,并存放到excel表格中。
(1)新建一个Excel工作簿,打Excel VB编辑器。
(2)在该工程下,建立一个窗体,在窗体中添加一个按钮,
编辑窗口。
(3)在过程中输入以下代码:
Private Sub CommandButtonl_ Click()
Dim lcConnectionString, lcCommandText As String
Dim loADODBConnection As ADODB.Connection
Dim loADODBRecordset As ADODB.Recordset
,和Access钩通的连接字符串
lcConnectionString-"Driver-(Microsoft Access
双击该按钮,切换到代码
Driver (".mdb));”、‘
"DBQ-C八dbl.mdb;一‘
"ReadOnly-True"
,提取而要信息
lcCommandText-一select二‘
Set loADODBConnection一CreateObject("ADODB.Connection")
Set loADODBRecordset,CreateObject("ADODB.Recordset")
loADODBConnection.Open 1cConnectionString
loADODBRecordset.Open lcCommandText, loADODBConnection, 3, 1, 1
存入Excel中
Dim r, f As Integer
r一1
For f二0 To loADODBRecordset.Fields.Count一1
Sheets(1).Cells(r, f+1)一loADODBRecordset.Fields(f).Name
Next
While
r
Not loADODBRecordset.EOF
For f=
;,。
loADODBRecordset.Fields.Count一1
Sheets(1).Cells(r, f+1)一loADODBRecordset.Fields(f).Value
Next
1oADODBRecordset.MoveNext
wend 关闭连接
1oADODBConnection.Close
衰格自适应宽度
Sheets(1).Ce11s.EntireColumn.AutoFit
End Sub
读者重点要学习一下连接字符串:
1cConnectionString-"Driver-(Microsoft Access Driver (".mdb));
一DBQ-C八dbl. mdb;"‘"ReadOnly-True"
以上连接字符申将连接驱动改为Driver-(Microsoft Access Driver (*.mdb)),并利用DBQ
乡数.设置数据路径为C: dbl.mdb.当建立数据连接时,以上代码会直接打开db l.mdb。而
代码中查询的SQL语句如下:
select .from author
上面的SQL语句将查询author*中的所有数据。执行以上语句,筛选的结果如图6.13所
示。
这样,就可以成功利用VBA语句调用Access数据库中的信息了。数据操作范围进一步
扩大。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
在Word2010文档中使用"粘贴选项"
![](https://img.aspxhome.com/file/2023/8/22208_0s.jpg)
word中怎样设置超链接
Win10截图工具失效怎么办?这个方法帮你轻松修复
![](https://img.aspxhome.com/file/2023/7/48977_0s.jpg)
Win10怎么使用命令卸载IE浏览器?Win10系统卸载IE浏览器的方法
![](https://img.aspxhome.com/file/2023/9/51189_0s.png)
为什么 Excel 2007 中的数字显示不正确 ?
![](https://img.aspxhome.com/file/2023/3/38913_0s.png)
WPS表格中如何在两张工作表中找出相同的内容
Word文档中的图片如何压缩?
![](https://img.aspxhome.com/file/2023/5/24825_0s.jpg)
WPS excel怎么在斜杠里打字
![](https://img.aspxhome.com/file/2023/6/a140686_0s.jpg)
batchplot怎么用?cad批量打印batchplot使用教程
![](https://img.aspxhome.com/file/2023/4/14934_0s.jpg)
如何使用LibreOffice将docx.doc等word文档转成PDF
![](https://img.aspxhome.com/file/2023/5/21195_0s.png)
word怎么复制格式
![](https://img.aspxhome.com/file/2023/7/34447_0s.gif)
word 段前分页怎么设置?
![](https://img.aspxhome.com/file/2023/3/33213_0s.png)
excel2016怎么创建漂亮的垂直框列表?
![](https://img.aspxhome.com/file/2023/9/40159_0s.jpg)
联想电脑怎么把Win10系统改为win7系统?
![](https://img.aspxhome.com/file/2023/2/51762_0s.png)
iOS 15 中的“播报通知”功能如何使用?
![](https://img.aspxhome.com/file/2023/7/45627_0s.png)
Excel 2019 如何求解二元一次方程图解
![](https://img.aspxhome.com/file/2023/0/a140960_0s.jpg)
Word表格操作常用技巧三则
如何修改Excel图表背景
![](https://img.aspxhome.com/file/2023/8/36378_0s.jpg)
Excel如何合并多行数据
![](https://img.aspxhome.com/file/2023/8/55048_0s.gif)
Word上标快捷键是什么?
![](https://img.aspxhome.com/file/2023/9/32289_0s.png)