Excel中使用VBA訪問Access資料庫

2022-08-30 00:30:21 字數 2794 閱讀 9170

excel中使用vba的優點:

巨集是vba的一種簡單應用。巨集可以通過編寫vba、錄製巨集兩種方式獲得。通常是先錄製巨集,再在獲得的巨集的基礎上進行語句優化調整,最後得到想要的巨集。

在《誰說菜鳥不會資料分析(工具篇)》第四章 讓報告自動化中,涉及到根據輸入日期,從access資料庫中提取相關資料到excel中相關操作。

進行編寫**前的準備工作:

excel中用vba根據輸入的日期從access資料庫中提取相應的資料並插入到excel表中:

sub 資料提取()

'定義資料庫鏈結物件adoconn

dim adoconn as adodb.connection

'定義資料庫存放路徑

dim mydata as string

'定義日期變數

dim d1 as date

'定義日期變數

dim d2 as date

'定義表示ecxel行數的變數

dim n as integer

'定義sql字串

dim strsql1 as string

'定義sql字串

dim strsql2 as string

'定義sql字串

dim strsql3 as string

'定義sql字串

dim strsql4 as string

'初始化資料庫連線物件

set adoconn =new adodb.connection

'指定資料庫,該資料庫放在當前excel檔案目錄中,且名為「業務資料庫.accdb」

mydata = thisworkbook.path & "

\業務資料庫.accdb"'

日期輸入對話方塊中的日期賦值給d1

d1 = inputbox("

請輸入需要提數的日期,例如:2011-9-4

", "

提數日期")

'將d2賦值為d1+1

d2 = d1 + 1

'將資料來源表中第三列第乙個空格單元格的行數賦值給n

n = activesheet.range("

c1").end(xldown).row + 1debug.print n

'建立資料庫鏈結,開啟指定的資料庫mydata

with adoconn

.provider = "

microsoft.ace.oledb.12.0

".open mydata

end with

'在使用者明細表中根據輸入的日期查詢當天有多少使用者註冊

strsql1 = "

select count(使用者id) from 使用者明細 where 註冊日期<#

" & d2 & "

# and 註冊日期》=#

" & d1 & "#"

'在訂購明細表中根據輸入的日期查詢當天有多少使用者購買,注意去重

strsql2 = "

select count(使用者id) from (select distinct 使用者id from 訂購明細 where 訂購日期<#

" & d2 & "

# and 訂購日期》=#

" & d1 & "#)"

'在訂購明細表中根據輸入的日期查詢當天訂單數和業務收入

strsql3 = "

select count(訂單編號), sum(訂購金額) from 訂購明細 where 訂購日期<#

" & d2 & "

# and 訂購日期》=#

" & d1 & "#"

'在訂購明細表中根據輸入的日期查詢截止到當前累計訂購使用者,注意去重

strsql4 = "

select count(使用者id) from (select distinct 使用者id from 訂購明細 where 訂購日期<=#

" & d1 & "#)"

'將新增使用者數插入到資料來源表的當前時間行的新增使用者列

activesheet.cells(n, 3).copyfromrecordset adoconn.execute(strsql1)

'將訂購使用者數插入到資料來源表的當前時間行的訂購使用者數列

activesheet.cells(n, 4).copyfromrecordset adoconn.execute(strsql2)

'將訂單數和訂購金額插入到資料來源表當前時間行的訂單數和業務收入列

activesheet.cells(n, 5).copyfromrecordset adoconn.execute(strsql3)

'經累計訂購使用者數插入到資料來源表當前時間行的累計使用者數列

activesheet.cells(n, 7).copyfromrecordset adoconn.execute(strsql4)

'測試資料庫是否連線成功

'if adoconn.state = adstateopen then

'msgbox "連線成功"

'adoconn.close

'end if

msgbox

"資料提取完畢"'

釋放變數

set adoconn =nothing

end sub

該巨集是繫結在乙個按鈕控制項上的,點選該按鈕,會彈出輸入日期提示框,根據提示輸入日期,就可以從資料庫中提取資料到excel表中。

**中訪問的資料庫是和excel表放在同一目錄下的,所以用thisworkbook.path來構造的資料庫路徑。也可以使用資料庫的絕對路徑。

EXCEL中使用VBA取有效使用區域

原創 牛超 2009 06 osaka 如題,修改原來的指令碼,引用usedrange private sub fillvalueauto astr as string,currow as long dim svalue as string dim sbatname as string dim sp...

excel中使用VBA將單元格的內容轉為多行

功能實現 將sheet1中a1單元格的值拆分後 顯示到sheet2的a列中 private sub worksheet change byval target as range 只有a1單元格的值改變才會執行 if target.address a 1 then 定義變數 dim x as inte...

Excel中使用VBA進行度分秒與十進位制度的轉換

發現excel的vba功能真是批量處理的一把利刃,工作中小試牛刀了一把,將excel中度分秒形式的座標批量處理成十進位制度形式,處理完後用於gis展點製圖。原excel資料如下 vba 如下 1 subcoorder 2dim longitude,latitude as string arr 3di...