简体   繁体   中英

Excel: Saving query results directly to CSV file

I have a dataset in Excel, of which I have to save an assorted part to a new csv file. I have used SQL to select the part required to be saved. I was hoping somebody would guide me about saving this selection to csv using SQL.

SQL gives me a recordset but I would like to loop through it only as a last resort. I am hoping there is a better approach that directly saves the entire result from within the query itself if possible.

Something like the solution by Remou on Want VBA in excel to read very large CSV and create output file of a small subset of the CSV is what I'm looking for. But unfortunately I can't get that to work.

Assuming you are in Excel VBA, has an ADODB opened with a Recordset object connected to a database and you want to save the content into a CSV (from within the Excel VBA).

The easiest is actually still by looping through the records in the recordset.

However, since you already rule that out (for whatever reasons), the next option would be to use the Recordset.Save <StreamObject> method. Create a System.IO.Streamwriter object to pass to the Recordset.Save .

OR, another way if you are using Jet SQL is:

conDB.Execute "SELECT * INTO [Text;Database=" _
               & vsCSVFolder _
               & ";HDR=No;FMT=Delimited].[" _
               & vsCSVFileame _
               & "] FROM Attendance", _
                 DBExport, _
                 adCmdText Or adExecuteNoRecords

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM