技術(shù) 點
- 技術(shù)
- 點
- V幣
- 點
- 積分
- 6865
|
本帖最后由 紅塵如煙 于 2010-10-18 23:32 編輯
使用示例:
導(dǎo)出窗體數(shù)據(jù): ExportToExcel Me.Recordset, "C:\Test.xls"
導(dǎo)出子窗體數(shù)據(jù):ExportToExcel Me.子窗體.Form.Recordset, "C:\Test.xls"
導(dǎo)出列表框數(shù)據(jù):ExPortToExcel Me.List1.Recordset, "C:\Test.xls"- '======================================================================================================
- '函數(shù)名稱: ExportToExcel
- '功能描述: 將記錄集中的數(shù)據(jù)導(dǎo)出到Excel文件
- '輸入?yún)?shù): rst 必需的,用于導(dǎo)出數(shù)據(jù)的打開的記錄集對象,可以使用窗體的Recordset屬性
- ' FileName 必需的,導(dǎo)出的Excel文件存放路徑名
- '返回參數(shù): 成功導(dǎo)出返回True,否則返回False
- '使用說明: 可以對綁定窗體進行篩選,然后將窗體的Recrodset屬性傳遞給rst參數(shù),這樣就可以將篩選結(jié)果導(dǎo)出,另
- ' 外還可以用于導(dǎo)出列表框、組合框中的數(shù)據(jù),同樣只需要傳遞Recordset屬性即可
- '兼 容 性: 必須安裝Excel,但無需引用
- '作 者: 紅塵如煙
- '創(chuàng)建日期: 20010-10-14
- '======================================================================================================
- Function ExportToExcel(rst As Object, FileName As String) As Boolean
- On Error GoTo Err_ExportToExcel
- Dim objExcelApp As Object
- Dim objExcelBook As Object
- Dim objExcelSheet As Object
- Dim objExcelQuery As Object
-
- If rst.RecordCount =0 Then
- MsgBox ("沒有數(shù)據(jù)可導(dǎo)出!"), vbExclamation
- GoSub Exit_ExportToExcel
- End If
-
- If Dir(FileName) <> "" Then Kill FileName
-
- DoCmd.Hourglass True
-
- Set objExcelApp = CreateObject("Excel.Application")
- Set objExcelBook = objExcelApp.Workbooks().Add()
- Set objExcelSheet = objExcelBook.Worksheets("sheet1")
-
- Set objExcelQuery = objExcelSheet.QueryTables.Add(rst, objExcelSheet.Range("A1"))
- With objExcelQuery
- .FieldNames = True
- .FillAdjacentFormulas = False
- .PreserveFormatting = True
- .BackgroundQuery = True
- .RefreshStyle = 1 ' xlInsertDeleteCells
- .SavePassword = True
- .SaveData = True
- .AdjustColumnWidth = True
- .RefreshPeriod = 0
- .PreserveColumnInfo = True
- End With
-
- objExcelQuery.Refresh
-
- objExcelBook.Worksheets("sheet1").SaveAs FileName
- ExportToExcel = True
- If MsgBox("數(shù)據(jù)已導(dǎo)出,是否打開并查看?", vbQuestion + vbYesNo) = vbYes Then
- objExcelApp.Visible = True
- Else
- objExcelBook.Saved = True
- objExcelApp.Quit
- End If
-
- Exit_ExportToExcel:
- Set objExcelApp = Nothing
- Set objExcelBook = Nothing
- Set objExcelSheet = Nothing
- Set rst = Nothing
- DoCmd.Hourglass False
- Exit Function
-
- Err_ExportToExcel:
- If Err = 70 Then
- MsgBox "無法刪除文件 '" & FileName & "',可能該文件已被打開或沒有權(quán)限。", vbCritical
- Else
- MsgBox Err.Source & " #" & Err & vbCrLf & vbCrLf & Err.Description, vbCritical
- End If
- Resume Exit_ExportToExcel
- End Function
復(fù)制代碼 |
|