'**************************************
' 过程名: Recordset2Excel
' 描 述:使用ADO Recordset对象把记录导入到Excel文件中
'
' 输 入:ADO Recordset
'
'****************************************
Public Sub Recordset2Excel(rstSource As ADODB.Recordset)
Dim xlsApp As Excel.Application
Dim xlsWBook As Excel.Workbook
Dim xlsWSheet As Excel.Worksheet
Dim i, j As Integer
' 获取或者建立 Excel 对象
On Error Resume Next
Set xlsApp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set xlsApp = New Excel.Application
Err.Clear
End If
' 建立 WorkSheet
Set xlsWBook = xlsApp.Workbooks.Add
Set xlsWSheet = xlsWBook.ActiveSheet
' 导出 ColumnHeaders
For j = 0 To rstSource.Fields.Count
xlsWSheet.Cells(2, j + 1) = rstSource.Fields(j).Name
Next j
' 导出 Data
rstSource.MoveFirst
For i = 1 To rstSource.RecordCount
For j = 0 To rstSource.Fields.Count
xlsWSheet.Cells(i + 2, j + 1) = rstSource.Fields(j).Value
Next j
rstSource.MoveNext
Next i
rstSource.MoveFirst
' 自适应行标题
For i = 1 To rstSource.Fields.Count
xlsWSheet.Columns(i).AutoFit
Next i
xlsWSheet.Range("A1").Select
' 显示 Excel
xlsApp.Visible = True
Set xlsApp = Nothing
Set xlsWBook = Nothing
Set xlsWSheet = Nothing
End Sub
转自:枕善居
更多精彩>>>
如果觉得《[VB]使用ADO Recordset对象导入Excel》对你有帮助,请点赞、收藏,并留下你的观点哦!