Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, 2013, 2016, 2019, and Excel in Office 365. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Specifying a Delimiter when Saving a CSV File in a Macro.

Specifying a Delimiter when Saving a CSV File in a Macro

by Allen Wyatt
(last updated February 26, 2020)

4

When using the tools available from the ribbon to export a worksheet, as a CSV file, Arkadiusz noted that he can specify that he wants to use a semicolon (;) as a field delimiter. However, if he saves a CSV file using a macro (FileFormat:=xlCSV or xlCSVWindows), then he cannot specify a semicolon as a delimiter.

This works this way by design in VBA. The Excel implementation of the export routines for VBA always use whatever the Windows regional settings are to determine how items in a CSV should be separated. Specifically, the routine looks at the List Separator field for the delimiter. This means that you can, if desired, change the delimiter to a semicolon by changing the List Separator setting in your regional settings configuration.

If you don't want to change the regional settings, then you can instead write your own macro that will output the file in any way you desire. Consider, for a moment, the following macro, which will output the file:

Sub CreateFile()
    Dim sFName As String
    Dim Rows As Long
    Dim Cols As Long
    Dim J As Long
    Dim K As Long
    Dim sTemp As String
    Dim sSep As String

    sSep = ";"  'Specify the separator to be used

    sFName = ActiveWorkbook.FullName
    If Right(sFName, 5) = ".xlsx" Then
        sFName = Mid(sFName, 1, Len(sFName) - 5)
        sFName = sFName & ".txt"
        Open sFName For Output As 1

        With ActiveSheet
            'Number of rows to export is based on the contents
            'of column B. If it should be based on a different
            'column, change the following line to reflect the
            'column desired.
            Rows = .Cells(.Rows.Count, "B").End(xlUp).Row
            For J = 1 To Rows
                sTemp = ""
                Cols = .Cells(J, .Columns.Count).End(xlToLeft).Column
                For K = 2 To Cols
                    sTemp = sTemp & .Cells(J, K).Value
                    If K < Cols Then sTemp = sTemp & sSep
                Next
                Print #1, sTemp
            Next J
        End With

        Close 1

        sTemp = "There were " & Rows & " rows of data written "
        sTemp = sTemp & "to this file:" & vbCrLf & sFName
    Else
        sTemp = "This macro needs to be run on a workbook "
        sTemp = sTemp & "stored in the XLSX format."
    End If

    MsgBox sTemp
End Sub

This macro opens a text file that has the same name as your workbook. It then steps through each row and starts putting together a string of the cell contents. (This is put into the sTemp variable.) Each cell has a semicolon placed between it, as defined by the sSep variable. Each row's concatenated values are stored in the text file, and when done the text file is closed. The routine is very quick, and when done it displays a message indicating how many rows were exported to the file.

Note:

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (9243) applies to Microsoft Excel 2007, 2010, 2013, 2016, 2019, and Excel in Office 365. You can find a version of this tip for the older menu interface of Excel here: Specifying a Delimiter when Saving a CSV File in a Macro.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Inserting a Non-Breaking Hyphen

Non-breaking hyphens can come in helpful for some types of writing. They force the words (or characters) on both sides of ...

Discover More

Selecting a Chart Pattern

If you don't have Excel installed on your system, Microsoft Graph is a handy way to create simple charts for your ...

Discover More

Protecting a Table Column

Do you need a way to protect the information you put in a table? Word doesn't have a way to do this, but there are a few ...

Discover More

Professional Development Guidance! Four world-class developers offer start-to-finish guidance for building powerful, robust, and secure applications with Excel. The authors show how to consistently make the right design decisions and make the most of Excel's powerful features. Check out Professional Excel Development today!

More ExcelTips (ribbon)

Putting the Last Saved Date in a Cell

Do you need a cell in your worksheet to display the date on which the workbook was last saved? This can be a bit tricky, ...

Discover More

Inserting the Current Time with Seconds

If you need to insert the current time, with seconds, then you'll need the macro discussed in this tip. It's easy to use ...

Discover More

Determining if Calculation is Necessary

When processing a worksheet with a macro, it may be helpful to periodically recalculate the worksheet. Wouldn't it be ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is nine minus 2?

2015-02-07 02:57:07

navuser1

I want to export my table data into a csv file using excel automation in my programming.

I also want the double quote (") as a Field Start/End Delimiter and | as Field Separator.

how to get this ?


2015-01-28 07:55:04

Hans

As for the comment "Specifically, the routine looks at the List Separator field for the delimiter. This means that you can, if desired, change the delimiter to a semicolon by changing the List Separator setting in your regional settings configuration.":

I can rebut: My regional settings has for years had ";" as list separator, yet xlCSV yields ","s.


2014-04-29 08:45:50

Bryan

Oh. My. Goodness. There are so many terrible things in this macro. It clearly was written pre-2007 and never updated.

* You haven't declared ANY of your variables. There's simply no reason to skip this step.
* As Jeff C mentioned, you are assuming that the ONLY extension available is .xls. Either of his two solutions would work, depending on your desired outcome
* The Range("B65000").End(xlUp).Row is an antiquated function that could have failed even in xl2003 and before: it's based on the assumption that there's no data beyond row 65000, but xl2003 had 65,536 rows, and xl2007+ has 1,048,576 rows! Plus, if there's data in row 65,000, then you've added new ways for the call to fail.
* Similarly, the "HA1" references aren't correct either. The last column in xl2003 was IV, not HA, and the last row in xl2007 is XFD. Plus, I don't understand why (1) you would only reference the first row in determining how wide your data is, and (2) why you call the exact same function once for every row in your data, when you could save it to a variable and reference the variable instead. (Ok, I thought about it, and perhaps (1) is because you want to write null/blanks into your data, and you are assuming that there's a column header for each column containing data).
* Both the width/height could utilize the Worksheet.UsedRange object, or a myriad of other ways to find the height and width that don't rely on hard-coded cell values. Heck, why not just use For Each rng in UsedRange, then instead of having to have i and j to keep track of the row and column, you just have your rng variable which keeps track of it all at once.
* This part isn't *so* terrible, but I think instead of checking on every row if you have reached the last column, I find it easier to just add the separator at every iteration of the loop then remove the last separator after the loop.
* Speaking of separators, the whole purpose was to be able to define your own. This should at a minimum be saved as a constant at the top instead of a string literal buried within the code.
* Columns(1).Select / Selection.Copy... really? Columns(1).Copy
* Workbooks.Add returns a workbook object, so you can say With Workbooks.Add and not rely on a hope and a prayer using ActiveSheet and ActiveWorkbook
* You forgot to delete the column at the end.

Really, the whole concept of inserting a column is pretty silly. It makes so much more sense to read the rows into a string variable then write the whole thing to a text file. Or if you don't want to worry about the I/O functions (I always forget how they work... one of these days I'll write a class to encapsulate them all so I don't *have* to remember how they work), save each row to a slot in a variant array, plop the variant array into your new workbook.


2014-04-28 09:11:12

Jeff C

The code to get FName is a bit outdated since the extension for the active workbook name could be different (xlsx, xlsm, etc.). You can always parse the name based on the last period character found, but why not just omit this code altogether and just append ".txt" to the name (MyWorkbook.xlsx.txt)?


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.