In this article, I am going to teach you 4 VBA Methods of – how to export data from Excel Range to a CSV file format using Excel VBA.
 Did you know?
CSV is an abbreviation of Comma Separated Value. As the name suggests, it is clear that this file stores the tabular data in a format where data is separated by comma.
Interestingly, CSV is also a plain text file type. Here each line represents a row and each value separated by comma, resides in columns.
Important Note: Since comma is used as delimiter in CSV file – so what if your data itself has comma (,) as a value? To overcome this issue, CSV file format, stores such values within double quotes (” “) and then separated by comma(,).
Let’s get started then…
Methods of Exporting Excel data to CSV Files using VBA
In this article, following are the methods which I am using to Export Excel data i CSV format.
Before we go in to details, I would like to recommend you guys to go through following tutorials – this will help you in understanding the code better –
In following tutorial about interaction with text files through Excel VBA, we have talked a lot about creating new text files, exporting data from an Excel Range to Text file and so many other different topics.
VBA Guide to Interact with Text Files – Part – 1
VBA Guide to Interact with Text Files – Part – 2
1. Export ActiveWorkSheet as CSV file
Advantages of this method
1. This is a very simple and quickest method to export your Excel data to a CSV file.
2. No extra coding required in order to maintain the comma delimiter or double quotes etc. Excel does it by itself.
At the same time, this method has some short comings or challenges as well.
Drawbacks of this Method
1. In this method, data from ActiveSheet is saved as CSV file only. It ignores rest other sheets and its data.
2. You do not have control over data – which one to be exported or ignored. It will export every single data from the sheet to CSV format.
For example: If you have some blank rows at the beginning of the sheet etc., which you do not want to save it in CSV, it is not possible to ignore them. It will still save those lines as blank values in the CSV.
Best case when it should be used?
This is the best option, when your excel sheet has, the only data which you want to export it as a CSV file. That means it does not have any other data which you want to ignore while exporting it to csv.
VBA Code
Sub saveSheetToCSV()
Dim myCSVFileName As String
Dim tempWB As Workbook
Application.DisplayAlerts = False
On Error GoTo err
myCSVFileName = ThisWorkbook.Path & "\" & "CSV-Exported-File-" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
ThisWorkbook.Sheets("YourSheetToCopy").Activate
ActiveSheet.Copy
Set tempWB = ActiveWorkbook
With tempWB
.SaveAs Filename:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
err:
Application.DisplayAlerts = True
End Sub
Explanation of the Code
This method is simply using the SaveAs feature of ActiveSheet to CSV format. Rest is self explanatory.
2. VBA to Export Specific Range to CSV – Method 1
Advantages of this method
This method overcomes both the challenges of the first Method.
1. Here you have full control over which all data you want to be part of your CSV file.
2. You can read data from random places and even from different sheets as well.
3. You can use your own delimiter – For example: instead of comma, you may use semicolon(;)
Drawbacks of this Method
1. The only shortcoming with this method, as compared to first method, is it has few more lines of code and execution time will be more because you are reading data for each row and column and putting them together in CSV file – separating them by comma.
Best case when it should be used?
1. When your data is scattered
2. You want to have control over data (Format check, some transformation logic etc.)
VBA Codes
Sub exportRangeToCSVFile()
Dim myCSVFileName As String
Dim myWB As Workbook
Dim rngToSave As Range
Dim fNum As Integer
Dim csvVal As String
Set myWB = ThisWorkbook
myCSVFileName = myWB.Path & "\" & "CSV-Exported-File-" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
csvVal = ""
fNum = FreeFile
Set rngToSave = Range("B2:H30")
Open myCSVFileName For Output As #fNum
For i = 1 To rngToSave.Rows.Count
For j = 1 To rngToSave.Columns.Count
csvVal = csvVal & Chr(34) & rngToSave(i, j).Value & Chr(34) & ","
Next
Print #fNum, Left(csvVal, Len(csvVal) - 2)
csvVal = ""
Next
Close #fileNumber
End Sub
Explanation of above Code
In above code, I am doing the following:
1. It is a simple for loop, using which I am concatenating each row and columns data separated by comma (,)
2. Print each rows data in csv file.
3. That’s all… your csv file is ready to use
3. VBA to Export excel Range or Table to csv – Method 2
If you want a specific range or Table to be exported as CSV from a Worksheet, which has lot more other data as well that you want to ignore, then this method should be used. Most importantly data is huge and chances are that your data might have comma (,) or double quotes (” “) as part of values.
How this method works?
Step 1: Copy the Range or Table data in to a New WorkSheetat Cell A1
Step 2: Now this new Worksheet has “the only data” which you want to save as CSV, therefore, apply method 1 and saveAs this WorkSheet as CSV file.
Best case when it should be used?
1. When you have a clear range of data which you want to export as csv
2. Data is large enough.
3. When there are chances that your data might have comma or double quotes as a value
VBA Code
Sub saveRangeToCSV()
Dim myCSVFileName As String
Dim myWB As Workbook
Dim tempWB As Workbook
Dim rngToSave As Range
Application.DisplayAlerts = False
On Error GoTo err
Set myWB = ThisWorkbook
myCSVFileName = myWB.Path & "\" & "CSV-Exported-File-" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
Set rngToSave = Range("C3:H50")
rngToSave.Copy
Set tempWB = Application.Workbooks.Add(1)
With tempWB
.Sheets(1).Range("A1").PasteSpecial xlPasteValues
.SaveAs Filename:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
err:
Application.DisplayAlerts = True
End Sub
VBA Code Explanation
Above VBA Code is doing the followings:
1. Copy the Range from your Excel Sheet – rngToSave
2. Create a new Excel Workbook
3. Paste the Copied range data in to the first sheet of the workbook from A1 cell – .Sheets(1).Range(“A1”).PasteSpecial xlPasteValues
4. SaveAs this new workbook as CSV file
5. You are done Now 🙂
4. VBA to Export excel Table to CSV format
This is the simplest method to save an excel table to CSV format. Most importantly – your data must NOT have comma (,) as part of values. In such case, you should use above method – 3.
VBA for saving Excel Table as CSV
Sub saveTableToCSV()
Dim tbl As ListObject
Dim csvFilePath As String
Dim fNum As Integer
Dim tblArr
Dim rowArr
Dim csvVal
Set tbl = Worksheets("YourSheetName").ListObjects("YourTableName")
csvFilePath = "C:\Users\vmishra\Desktop\CSVFile.csv"
tblArr = tbl.DataBodyRange.Value
fNum = FreeFile()
Open csvFilePath For Output As #fNum
For i = 1 To UBound(tblArr)
rowArr = Application.Index(tblArr, i, 0)
csvVal = VBA.Join(rowArr, ",")
Print #1, csvVal
Next
Close #fNum
Set tblArr = Nothing
Set rowArr = Nothing
Set csvVal = Nothing
End Sub
Explanation about the VBA Code above
Above code is doing the following
1. Storing the whole content of your table into a two dimensional array – tblArr
2. For each row – extract the data in to one dimensional array rowArr
3. Join all the data of single dimensional array by using comma as delimiter and store it in to a variable – csvVal
4. Print this comma separated data in the csv file (which was created)
5. Repeat this process for each row of the table – For loop is used to do so
I have tried covering all possible methods to export your excel data to CSV format.
I would really appreciate, if you provide your feedback. Do let me know by writing your comment here in the comment section of this article.
Did you like this article?
Then share it with your friends… spread knowledge…Learn All about interacting with Text Files in Excel VBA like opening, creating, writing, reading etc. from Text Files using Excel VBA code
Expanding on Method 3, how would you copy two columns to a csv file? For example, all the data in column A and Column E.
thanks, I needed to convert a range of data to csv format but file needed to be named .txt not name.csv. this was surprisingly hard.
your method allowed me perform this task without save sheet as type and all that entails. this method lets me manipulate the .TXT file with fresh excel data without saving excel
Dear Bruce,
I am glad that it helped you. thanks for your feedback.
Using the example (2. VBA to Export Specific Range to CSV – Method 1) how can you save to a specific folder within the desktop like ChDir “C\Users\nesbie\Desktop\FolderName” or even better, just add a button on Excel that will automatically save to that folder and give you the print box so you can select a printer and print (like it would automatically save without even notifying the user?)
Thank you!
Chris
I have a workbook with data on 18 rows, I want data of first 1-3 columns in row one, 4-6 in row 2, 7-9 in row 3 so on. Do we have any specific function or code to execute this.
HI!
in the method 4, how can I save the table with column headers?
thx!! 🙂
Hi Yes.. you can do so .. instead of using the statement
It will do the job.
how can i add column headers with method 2?
thx 🙂
Hello,
I am reviewing this four methods. Which one would you prefer to detect empty rows (at least with column X value empty). Also, which will you prefer to save only some colums.
Many thanks
Awesome, thanks! I believe there is a small error at the end of (2) Direct Export Method 1…
[ Close #fileNumber ] did not close the file after writing (the file would think it was still open via Excel)
Changing it [ Close #fNum ] seem to do the trick.
Cheers!
I am trying your very good example, but when I try to use it together with autofiltering the table is not exporting the filtered data can you help?
Set tbl = Worksheets(“FOR EXPORT”).ListObjects(“MyTable”)
‘SET AUTOFILTER
tbl.Range.AutoFilter Field:=3, Criteria1:=”*ERROR*”
Set VisRng = tbl.Range.SpecialCells(xlCellTypeVisible)
‘ copy only the visible cells in range to array
tblArr = VisRng.Value
Hi,
I’ve used this code but my date is always exported with a hyphen rather than a forward slash. The program I am then importing this data to does not accept this format. Is there a way to format the date in the csv file with forward slashes rather than hyphens.
I’ve tried changing the format of the column in excel, that doesn’t work
Does changing
VBA.Format(VBA.Now, “dd-MMM-yyyy hh-mm”)
to
VBA.Format(VBA.Now, “dd/MMM/yyyy hh-mm”) work?
Great. Thanks a lot.
Is there a way to force UTF-16 encoding?
Charset = “utf-16”
I have tried Method 3, but it does not work in MAC Excel. It creates new file with the data but doesn’t save and close.
The first one, “1. Export ActiveWorkSheet as CSV file” works perfectly but how can I adjust export to multiple CSV, based of the value of a column? Thanks in advance
This is Great, Had 2 questions on Case 4. How can i only export rows that have values (currently its exporting even empty table rows). And for the file naming, is it possible to add a date variable for the file?
such as
csvFilePath = “C:\TEST\TEST&Date&.csv”
VBA noob here , thanks in advance 🙂
Hi,
Thanks very much for this tutorial, helped me a lot.
I tried listing 2 and found that it had 2 bugs:
1. Print #fNum, Left(csvVal, Len(csvVal) – 2) should be Print #fNum, Left(csvVal, Len(csvVal) – 1)
2. Close #fileNumber should be Close #fNum
Cheers!
Brian
Thank you for this! I was looking for a simple way to save a worksheet as a CSV. I modified the code to suite my needs, and save to a specific folder.
Hello, Thanks for this i do have a question regarding version 4 on the line
rowArr = Application.Index(tblArr, i, 0) i get a runtime error 13 type mismatch
does anyone have any ideas
Thank you so much for the effort in making this, I was looking for a simple option. I have adapted your code into my project
HOW TO SAVE DATA IN .CSV TEMPLET
This Code is not working. I am trying to save active excel sheet every min in csv format. first time it works from 2nd time i get error this macro can run. please check. thanks in advance
Public RunWhen As Double
Sub saveSheetToCSV()
Dim myCSVFileName As String
Dim tempWB As Workbook
Application.DisplayAlerts = False
On Error GoTo err
myCSVFileName = ThisWorkbook.Path & “\” & “CSV-Exported-File-” & VBA.Format(VBA.Now, “dd-MMM-yyyy hh-mm”) & “.csv”
ThisWorkbook.Sheets(“WorkArea”).Activate
ActiveSheet.Copy
Set tempWB = ActiveWorkbook
With tempWB
.SaveAs Filename:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
err:
Application.DisplayAlerts = True
End Sub
Sub StartTimer()
RunWhen = Now + TimeSerial(0, 1, 0)
Application.OnTime earliesttime:=RunWhen, procedure:=”saveSheetToCSV”, _
schedule:=True
End Sub
Sub StopTimer()
On Error Resume Next
Application.OnTime earliesttime:=RunWhen, _
procedure:=”saveSheetToCSV”, schedule:=False
End Sub
Private Sub Workbook_Open()
Call saveSheetToCSV
Call StartTimer
End Sub
Bonjour, there is a mistake in Method 1
Open myCSVFileName For Output As #fNum
For i = 1 To rngToSave.Rows.Count
For j = 1 To rngToSave.Columns.Count
csvVal = csvVal & Chr(34) & rngToSave(i, j).Value & Chr(34) & “,”
Next
Print #fNum, Left(csvVal, Len(csvVal) – 2)
csvVal = “”
Next
Close #fileNumber
–> The close file should be “Close #fileNumber” in lieu of “Close #fileNumber”
Thank you, this code was helpful
Great material to compare and to start with. Thanks a lot!
Have chosen and modified the second chapter because of the flexibility.
One comment: Putting the “Print” behind the loop makes it much quicker.