個人認為分為三種情況:
整個資料庫轉化為表格,從資料庫選擇部分資料轉化為表格,從特定記錄中選擇資料轉化為表格
1)整個資料庫轉化為表格
Private Sub Command1_Click()
Dim acApp As Access.Application
Dim strReportName As String
Dim strReportPath As String
Const SAMPLE_DB_PATH As String = "c:/EastRiver.mdb"
strReportName = "akaoqin "
strReportPath = "c:/"
' Start Access and open Northwind Traders database.
Set acApp = GetObject(SAMPLE_DB_PATH, "Access.Application")
acApp.DoCmd.OutputTo acOutputQuery, strReportName, _
acFormatXLS, strReportPath & "autoxls.xls", True
End Sub
應該是效率最高的。TransferDatabase這條指令也能完成這個功能,用法一樣,大家可以試試。
2)從資料庫選擇部分資料轉化為表格
VB支援SQL語言的SELECT ... INTO語句,這使得你可以将一種資料庫輕松地轉換為另一種格式,也可以在同一種格式的資料庫中進行轉換。下面我們以将.MDB格式轉換為Excel形式為例。
首先,打開.MDB檔案。如
Dim dbSource As Database
Set dbSource = OpenDatabase("MY.MDB")
然後使用SELECT ... INTO語句轉換檔案。
dbSource.Execute("SELECT * INTO my IN 'c:/documents/xldata.xls' 'EXCEL 5.0;' FROM table1")
這裡,IN子句後面是轉換後的資料庫檔案名,'EXCEL 5.0;'表示Excel 5.0/95格式,也可以是其他VB支援的格式。
SELECT ... INTO建立新的表或資料庫,而如果要将資料追加到已經存在的資料庫中,可以使用INSERT ... INTO語句。
3)從特定記錄中選擇資料轉化為表格
一個将Access資料庫轉換為Excel的例子:
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim oldPointer As Integer 'used to save the current
Dim rPointer As Integer 'current saving record
Dim xlsPointer As Integer 'used to point out the position the current record saving
oldPointer = rs_com.Bookmark 'save current pointer of rs_com
xlsPointer = 2 'the first line of Excel sheet
Set xlApp = CreateObject("Excel.Application") 'create Excel application
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)
Hide
frmSaveProgress.Show 'show the progress status
rs_com.MoveFirst 'rs_com is a table of your database
Dim i As Integer
While Not rs_com.EOF 'save ecah record to Excel file
For i = 0 To x 'x =記錄數
xlSheet.Cells(xlsPointer, i + 1) = rs_com.Fields(i)
Next
frmSaveProgress.nextStep (rs_com.Bookmark / rs_com.RecordCount)
rs_com.MoveNext
xlsPointer = xlsPointer + 1
Wend
Unload frmSaveProgress 'end save to Excel file
frmDataOper.Show
xlBook.SaveAs (xlsFileName)
xlBook.Close
xlApp.Quit
另一種實作
Set xlApp = New Excel.Application
Set xlApp = CreateObject("Excel.Application")
'激活EXCEL應用程式
xlApp.Visible = False
'隐藏EXCEL應用程式視窗
Set xlBook = xlApp.Workbooks.Open(strDestination)
'打開工作簿,strDestination為一個EXCEL報表檔案
Set xlsheet = xlBook.Worksheets(1)
'設定工作表
datPrimaryRS.Recordset.MoveFirst
'datPrimaryRS為Data控件
If IsNull(datPrimaryRS.Recordset!姓名) = False Then
xlSheet.Cells(4, 2) = datPrimaryRS.Recordset!姓名
End If
If IsNull(datPrimaryRS.Recordset!性别) = False Then
xlSheet.Cells(4, 4) = datPrimaryRS.Recordset!性别
End If
If IsNull(datPrimaryRS.Recordset!民族) = False Then
xlSheet.Cells(4, 6) = datPrimaryRS.Recordset!民族
注意事項:
1、在VB工程中添加對Excel類型庫的引用
為了能從VB應用程式中通路Excel豐富的内部資源,使Excel應用程式運作得更快,需要在VB工程中添加對Excel類型庫的引用。具體步驟如下:
a)從VB5“工程”菜單中選擇“引用”;
b) 在“引用”對話框中選擇Excel類型庫:"Microsoft Excel9.0 Object Library";
c)單擊左邊小方框,使之出現“√”符号;
d)按“确定”退出。