当前位置:网站首页>VBA 连接Access数据库和Excle
VBA 连接Access数据库和Excle
2022-07-30 18:50:00 【OOQ】
VBA 连接数据库步骤:
1.创建连接对象
2.打开连接
3.执行SQL
4.关闭连接
5.释放连接对象
前提:在【工具】>【引用】ADO库
Sub conDatabase()
Dim con As ADODB.Connection '声明对象变量
Set con = New ADODB.Connection '创建对象变量
'Dim con As New ADODB.Connection ’这一行等效于以上两行
'建立数据库连接
'con.Open "provider=microsoft.ace.oledb.12.0;data source =" & ThisWorkbook.Path & "\test.accdb" '连接access数据库
'con.Open "provider=microsoft.ace.oledb.12.0;extended properties=excel 12.0;data source =" & _
ThisWorkbook.Path & "\数据.xlsx"
'以下写法等效于 con.Open
With con
.Provider = "microsoft.ace.oledb.12.0"
.ConnectionString = ThisWorkbook.Path & "\test.accdb"
.Open
End With
MsgBox "连接成功"
Dim sql As String
'sql = "insert into check(code,year,month,day) values ('1','2022','1','1')"
sql = "insert into m_check(m_code,m_year,m_month,m_day) values (3,2022,1,1)"
con.Execute (sql)
con.Close '关闭连接
Set con = Nothing '释放变量
End Sub
注意事项:
1. 创建连接的两种写法
Dim con As ADODB.Connection '声明对象变量 Set con = New ADODB.Connection '创建对象变量
Dim con As New ADODB.Connection ’这一行等效于以上两行
2.两种写法打开连接
con.Open "provider=microsoft.ace.oledb.12.0;data source =" & ThisWorkbook.Path & "\test.accdb" '连接access数据库
With con .Provider = "microsoft.ace.oledb.12.0" .ConnectionString = ThisWorkbook.Path & "\test.accdb" .Open End With
VBA使用SQL操作Excel,方法和上面连接Access操作相似只需将连接字符串更改成下面这种:
con.Open "provider=microsoft.ace.oledb.12.0;extended properties=excel 12.0;data source =" & _ ThisWorkbook.Path & "\数据.xlsx"
边栏推荐
猜你喜欢
智慧中控屏
运营 23 年,昔日“国内第一大电商网站”黄了...
【每日一道LeetCode】——191. 位1的个数
OSPF详解(4)
The sixteenth issue of eight-part article Balabala said (MQ)
SwiftUI iOS Boutique Open Source Project Complete Baked Food Recipe App based on SQLite (tutorial including source code)
LeetCode 练习——关于查找数组元素之和的两道题
CCNA-NAT协议(理论与实验练习)
Pytorch foundation -- tensorboard use (1)
Codeblocks + Widgets create window code analysis
随机推荐
After 23 years of operation, the former "China's largest e-commerce website" has turned yellow...
7.30模拟赛总结
The sixteenth issue of eight-part article Balabala said (MQ)
LeetCode Exercise - Two Questions About Finding Sum of Array Elements
CMake库搜索函数居然不搜索LD_LIBRARY_PATH
core sound driver详解
MySql中@符号的使用
【Pointing to Offer】Pointing to Offer 18. Delete the node of the linked list
Read the "Language Model" in one article
中集世联达工业级成熟航运港口人工智能AI产品规模化应用,打造新一代高效能智慧港口和创新数字港口,全球港航人工智能能领军者中集飞瞳
Swiper轮播图片并播放背景音乐
scrapy基本使用
One year after graduation, I was engaged in software testing and won 11.5k. I didn't lose face to the post-98 generation...
终端分屏工具Terminalx的使用
Two-point answer naked question (plus a little pigeonhole principle)
Anaconda Navigator stuck on loading applications
高精度加法
kotlin by lazy
arcpy获取要素类(属性表)包含的数目
Fixed asset visualization intelligent management system