VB icon

ADO Recordset to Excel

Submitted on: 1/27/2015 4:17:00 AM
By: Frank Ramos (from psc cd)  
Level: Intermediate
User Rating: By 20 Users
Compatibility: VB 6.0
Views: 983
     Exports an ADO recordset to Microsoft Excel.
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
' Name: ADO Recordset to Excel
' Description:Exports an ADO recordset to Microsoft Excel.
' By: Frank Ramos (from psc cd)
' Inputs:ADO Recordset
' Assumes:When done Excel is left open for user interact. Remember to reference Microsoft Excel Object and ActiveX Data Object Libraries in your Project.

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
 ' Get or Create Excel Object
 On Error Resume Next
 Set xlsApp = GetObject(, "Excel.Application")
 If Err.Number <> 0 Then
Set xlsApp = New Excel.Application 
 End If
 ' Create WorkSheet
 Set xlsWBook = xlsApp.Workbooks.Add
 Set xlsWSheet = xlsWBook.ActiveSheet 
 ' Export ColumnHeaders
 For j = 0 To rstSource.Fields.Count
xlsWSheet.Cells(2, j + 1) = rstSource.Fields(j).Name
 Next j
 ' Export Data
 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
 Next i 
 ' Autofit column headers
 For i = 1 To rstSource.Fields.Count
 Next i
 ' Move to first cell to unselect
 ' Show Excel
 xlsApp.Visible = True
 Set xlsApp = Nothing
 Set xlsWBook = Nothing
 Set xlsWSheet = Nothing
End Sub

Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Intermediate category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)

To post feedback, first please login.