Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

How to export ADO recordset to an Excel file
[ All Languages » VB »  Excel]

Total Hit ( 3288)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


Some times we have situation when we want to export ADO recordset to an excel file. Here is the code ...

Click here to copy the following block
Private Function ExportToExcelFile(strFileName As String, rsData As ADODB.Recordset) As Boolean
  On Error GoTo ExportToExcelFile_Failed
  Dim bolTemp As Boolean

  '//Use for early Binding --You need to add reference to Excel Library
  'Dim objXlsApp As Excel.Application
  'Dim objWB As Excel.Workbook
  'Dim objWS As Excel.Worksheet
  
  '//Use for Late Binding --//Intelisense wont be available at design time
  Dim objXlsApp, objWB, objWS
  
      
  Dim i As Long
  bolTemp = False
  Set objXlsApp = CreateObject("Excel.Application")  'open excel
  Set objWB = objXlsApp.Workbooks.Add  'open a workbook
  Set objWS = objWB.Worksheets(1)  'it should be worksheet1

  'Insert the header row
  For i = 0 To rsData.Fields.Count - 1
    objWS.Cells(1, i + 1).Value = rsData.Fields(i).Name
  Next i
  Debug.Print rsData.RecordCount
  Do While (Not rsData.EOF)

    For i = 0 To rsData.Fields.Count - 1
      objWS.Cells(rsData.AbsolutePosition + 1, i + 1).Value = rsData.Fields(i).Value
    Next i
    rsData.MoveNext

  Loop
  
  objWS.Columns("A:Z").EntireColumn.AutoFit
  
  objWB.SaveAs strFileName
  objWB.Close
  objXlsApp.Quit
  bolTemp = True


xit_proc:
  On Error GoTo xit_this
  If Not objWS Is Nothing Then Set objWS = Nothing
  If Not objWB Is Nothing Then Set objWB = Nothing
  If Not objXlsApp Is Nothing Then Set objXlsApp = Nothing

xit_this:
  ExportToExcelFile = bolTemp
  Exit Function
ExportToExcelFile_Failed:
  MsgBox "Error Source:Export to Excel File" & vbCrLf & "Error Description:" & Err.Description
  Resume xit_proc
End Function


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.