Export SQL Data to a Comma-Separated Value File

Use this code to create a comma-separated value (CSV) file from a recordset based on a SQL query. A number of applications, including Excel and Access, can read CSV files:

 Function CSVExport(sSQL As String, sDest As _	String) As BooleanOn Error goto Err_Handler	Set snpExport = db.OpenRecordset(sSQL, dbOpenSnapshot)	Open App.Path & "" & sDest For Output As #1	For iLoop = 0 To snpExport.Fields.Count _		 - 1     'Export Field Names 		sFieldText = "" & _			(snpExport.Fields(iLoop).Name)		Write #1, sFieldText;	Next	Write #1,	snpExport.MoveFirst	Do While snpExport.EOF = False		For iLoop = 0 To snpExport.Fields.Count - 1			sFieldText = "" & (snpExport.Fields(iLoop))			Write #1, sFieldText;		Next		Write #1,		snpExport.MoveNext	Loop	CSVExport = True	Exit FunctionErr_Handler	MSGBOX("Error: " & Err.Description)	CSVExport=FalseEnd Function
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: