Excel通過VB查詢Access數(shù)據(jù)庫
Sub 按鈕5_Click()
Dim uADO, rsADO As Object
Dim strPath, strSql As String
Dim i As Integer, ri As Integer
?Dim D1 As Date
? ? '定義日期變量
? ? Dim D2 As Date
? ? '定義表示Ecxel行數(shù)的變量
Set uADO = CreateObject("ADODB.Connection") '新建數(shù)據(jù)庫連接對(duì)象
Set rsADO = CreateObject("ADODB.RecordSet") '新建記錄集對(duì)象
strPath = ThisWorkbook.Path & "\人力資源管理系統(tǒng).mdb " '設(shè)置數(shù)據(jù)庫地址
uADO.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strPath '打開數(shù)據(jù)庫
?D1 = InputBox("請(qǐng)輸入需要提數(shù)的日期,例如:2011-9-4", "提數(shù)日期")
? ? ?'將D2賦值為D1+1
? ? D2 = D1 + 1
?
?strSql = "SELECT 訂單編號(hào),品名,型號(hào)1, 型號(hào)2,型號(hào)3, 重量, 件數(shù) FROM 個(gè)人簡(jiǎn)歷 WHERE 離開日期<#" & D2 & "# AND 離開日期>=#" & D1 & "#" '設(shè)置查詢語句
rsADO.Open strSql, uADO, 1, 3 '執(zhí)行查詢
Dim R As Range
Set R = ActiveSheet.Range("B2")
ActiveSheet.UsedRange.Clear
For i = 0 To rsADO.Fields.Count - 1
R.Offset(0, i).Value = rsADO.Fields(i).Name '輸出字段名
Next i
Set R = R.Offset(1, 0)
Do Until rsADO.EOF '循環(huán)查詢到數(shù)據(jù) 直到記錄最后一條
For i = 0 To rsADO.Fields.Count - 1
R.Offset(ri, i).Value = rsADO.Fields(i).Value '輸出數(shù)據(jù)表內(nèi)容
Next i
ri = ri + 1
rsADO.MoveNext '指向下一條記錄
DoEvents
Loop
rsADO.Close '關(guān)閉記錄集
Set uADO = Nothing
Set rsADO = Nothing
End Sub