′新建一個(gè)ActiveX DLL工程工程名為DbToExcel
′工程-->引用,引用Microsoft ActiveX Data Objects 2.6 Library
′Microsoft Excel 9.0 Objects Library
Option Explicit
Private Mcnnquery As ADODB.Connection ′定義ADO連接對(duì)象
Private Mrsquery As ADODB.Recordset ′定義ADO記錄對(duì)象
Dim ObjExcel As Excel.Application ′定義Excel對(duì)象
Dim ObjWorkBook As Excel.Workbook ′定義工作薄
Dim ObjSheet As Excel.Worksheet ′定義工作表
Dim ObjRange As Excel.Range ′定義用戶使用工作表的范圍
Private Property Set Connquery(ByVal Conn As ADODB.Connection)
Set Mcnnquery = Conn
End Property
Private Property Get Connquery() As ADODB.Connection
Set Connquery = Mcnnquery
End Property
Private Property Set Rsquery(ByVal Rs As ADODB.Recordset)
Set Mrsquery = Rs
End Property
Private Property Get Rsquery() As ADODB.Recordset
Set Rsquery = Mrsquery
End Property
′屬性方法共有三個(gè)參數(shù)
′strcnn 連接對(duì)象
′strrs 數(shù)據(jù)集對(duì)象
′strpath EXCEL文件
Public Sub DbtoExcel(Strcnn As ADODB.Connection, Strrs As ADODB.Recordset, Strpath As String)
Dim i As Integer, j As Integer
On Error GoTo Err
Set Connquery = Strcnn ′設(shè)置cnnquery屬性
Set Rsquery = Strrs ′設(shè)置rsquery屬性
Set ObjExcel = New Excel.Application
Set ObjWorkBook = ObjExcel.Workbooks.Open(Strpath) ′打開(kāi)EXCEL文件
Set ObjSheet = ObjWorkBook.ActiveSheet
Set ObjRange = ObjSheet.UsedRange ′用戶使用過(guò)的工作表范圍
For i = 1 To Rsquery.Fields.Count
ObjRange.Cells(1, i) = Rsquery.Fields(i - 1).Name
Next i
For j = 1 To Rsquery.RecordCount
For i = 0 To Rsquery.Fields.Count - 1
ObjRange.Cells(j + 1, i + 1) = Rsquery.Fields(i).Value
Next i
Rsquery.MoveNext
Next j
ObjExcel.Quit
Set ObjWorkBook = Nothing
Set ObjRange = Nothing
Set ObjSheet = Nothing
Set ObjExcel = Nothing
Err:
MsgBox Err.Number & " " & Err.Description
Set ObjWorkBook = Nothing
Set ObjRange = Nothing
Set ObjSheet = Nothing
Set ObjExcel = Nothing
End Sub
′文件-->生成DbToExcel.dll
′新建一個(gè)標(biāo)準(zhǔn)EXE工程
′工程-->引用Microsoft ActiveX Data Objects 2.6 Library
瀏覽,加載剛才生成的DLL文件
Option Explicit
Dim Conn As ADODB.Connection
Dim Rs As ADODB.Recordset
Dim DE As New DbtoExcel.Class1 ′定義一個(gè)類,DbToExcel.DLL內(nèi)Class1類的一個(gè)實(shí)例
Private Sub Command1_Click()
DE.DbtoExcel Conn, Rs, "c\1.xls"
End Sub
Private Sub Form_Load()
Set Conn = New ADODB.Connection
Set Rs = New ADODB.Recordset
Conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db.mdb;Persist Security Info=False"
Conn.Open
Rs.Open "select * from users", Conn, adOpenKeyset, adLockBatchOptimistic
End Sub