Private Sub ExportToExcel(sql As String, conStr As String) '输出电子表的函数
On Error GoTo EXPORT_ERR
Dim rs As Object
Dim xlApp
As Object
Dim xlBook
As Object
Dim xlSheet
As Object
Dim xlQuery
As Object
Set rs = CreateObject("Adodb.Recordset")
rs.CursorLocation = adUseClient
rs.Open sql, conStr
If rs.RecordCount < 1 Then
MsgBox ("没有记录!"), vbExclamation
Exit Sub
End If
Dim rowCount
As Integer
Dim colCount
As Integer
rowCount = rs.RecordCount '记录总数
colCount = rs.Fields.Count '字段总数
Set xlApp = CreateObject("Excel.Application")
Set xlBook = Nothing
Set xlSheet = Nothing
Set xlBook = xlApp.Workbooks().Add
Set xlSheet = xlBook.Worksheets("sheet1")
'添加查询语句,导入EXCEL数据
Set xlQuery = xlSheet.QueryTables.Add(rs, xlSheet.Range("a1"))
With xlQuery
.FieldNames = True
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
End With
xlQuery.Refresh
xlApp.Application.Visible = True
Set xlApp = Nothing
'"交还控制给Excel
Set xlBook = Nothing
Set xlSheet = Nothing
Set rs = Nothing
Exit Sub
EXPORT_ERR:
MsgBox Err.Source & vbCrLf & vbCrLf & _
Err.description, vbExclamation, "信息"
End Sub
给你一个高手的输出电子表格代码
使用方法
sql = SSQL 'SSQL为原先查询的语句
conStr = "provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & App.Path & "\数据库.mdb"
Call ExportToExcel(sql, conStr) '调用函数
只要引用正确就可使用,速度相当快