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.

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.