Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, and 2013. 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 April 26, 2014)

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()
    FName = ActiveWorkbook.Name
    If Right(FName, 4) = ".xls" Then
        FName = Mid(FName, 1, Len(FName) - 4)
    End If

    Columns(1).Insert Shift:=xlToRight

    For i = 1 To Range("B65000").End(xlUp).Row
        TempString = ""
        For j = 2 To Range("HA1").End(xlToLeft).Column
            If j <> Range("HA1").End(xlToLeft).Column Then
                TempString = TempString & _
                  Cells(i, j).Value & ";"
            Else
                TempString = TempString & _
                  Cells(i, j).Value
            End If
        Next
        Cells(i, 1).Value = TempString
    Next

    Columns(1).Select
    Selection.Copy
    Workbooks.Add
    Range("A1").Select
    ActiveSheet.Paste
    Application.CutCopyMode = False

    ActiveWorkbook.SaveAs Filename:=FName & ".txt", _
      FileFormat:=xlPrinter
End Sub

This macro takes a unique approach to creating the output file. What it does is to insert a column at the left of your worksheet, and then concatenates all the data to the right of that column into the newly inserted column A. It adds a semicolon between each field. Once that is done, it grabs the information it put into column A and writes it into a new workbook. This workbook is then saved to disk using the xlPrinter file format, which means that it is put out "as is" without any modification whatsoever.

If you prefer a more direct approach, writing the information directly to a file without making changes to your worksheet, take a look at the macro at this blog post:

http://www.dicks-blog.com/archives/2004/11/09/roll-your-own-csv/

The macro uses commas between each field, but it can be easily modified so that it uses semicolons instead.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (9243) applies to Microsoft Excel 2007, 2010, and 2013. 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

Updating Links in Copied Files

When you copy workbooks that contain links, you may be at a loss as to how to update those links. There are a couple of ways ...

Discover More

Limiting Choices in a Cell

Want to limit what a person can enter into a particular cell? You can use Excel's data validation feature to help enforce ...

Discover More

The EDATE Function

Want to figure a date a certain number of months in the future or past? The EDATE function may be just what you need for your ...

Discover More

Save Time and Supercharge Excel! Automate virtually any routine task and save yourself hours, days, maybe even weeks. Then, learn how to make Excel do things you thought were simply impossible! Mastering advanced Excel macros has never been easier. Check out Excel 2010 VBA and Macros today!

More ExcelTips (ribbon)

Adding Leading Zeroes to ZIP Codes

Import a bunch of ZIP Codes into Excel, and you may be surprised that any leading zeroes disappear. Here's a handy little ...

Discover More

Hiding Macros

Need to hide some macros in your workbook? There are three ways you can do it, as covered in this discussion.

Discover More

Selecting Columns in VBA when Cells are Merged

If you have a macro that selects different columns in a worksheet while processing information, you may get some undesired ...

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 more than 9?

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.