Private Sub ExportToExcel(cntDataCn As Connection, byval FileName As String)
dim strSQL As String
strSQL = "select a.数据1 as TYPE,b.数据2 as PLACE,b.数据3 as CD INTO [Excel 8.0;Database=" & FileName & "].[exceltable] " & "from a,b where a.id=b.id"
''cntDataCn 是一个已经存在的连接,请自己连接好。
cntDataCn.Execute strSQL
End Sub
'导出记录集数据到Excel
'你设置好 strOpen 查询语句就可以了
Public Function ExporToExcel(strOpen As String)
'*********************************************************
'* 名称:ExporToExcel
'* 功能:导出数据到EXCEL
'* 用法:ExporToExcel(sql查询字符串)
'*********************************************************
Dim Rs_Data As New ADODB.Recordset
Dim Irowcount As Integer
Dim Icolcount As Integer
Dim cn As New ADODB.Connection
Dim xlapp As New Excel.Application
Dim xlbook As Excel.Workbook
Dim xlsheet As Excel.Worksheet
Dim xlQuery As Excel.QueryTable
With Rs_Data
If .State = adStateOpen Then
.Close
End If
.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\db1.mdb"
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.Source = strOpen
.Open
End With
With Rs_Data
If .RecordCount < 1 Then
MsgBox ("没有记录!")
Exit Function
End If
'记录总数
Irowcount = .RecordCount
'字段总数
Icolcount = .Fields.Count
End With
Set xlapp = CreateObject("Excel.Application")
Set xlbook = Nothing
Set xlsheet = Nothing
Set xlbook = xlapp.Workbooks().Add
Set xlsheet = xlbook.Worksheets("sheet1")
xlapp.Visible = True
'添加查询语句,导入EXCEL数据
Set xlQuery = xlsheet.QueryTables.Add(Rs_Data, xlsheet.Range("a1"))
xlQuery.FieldNames = True '显示字段名
xlQuery.Refresh
xlapp.Application.Visible = True
Set xlapp = Nothing '"交还控制给Excel
Set xlbook = Nothing
Set xlsheet = Nothing