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.

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, 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

Self-Aware Macros

Sometimes it may be helpful for a macro to know exactly where it is being executed. This tip provides a way that you can ...

Discover More

Consolidating Changes under a Single User

When using Track Changes, you may want to have your edits appear to be those of a different user. Here's how to fool Word ...

Discover More

Spell Checking Your Document

One of the final touches that many people perform is to check the spelling of their document. This can help improve the ...

Discover More

Solve Real Business Problems Master business modeling and analysis techniques with Excel and transform data into bottom-line results. This hands-on, scenario-focused guide shows you how to use the latest Excel tools to integrate data from multiple tables. Check out Microsoft Excel 2013 Data Analysis and Business Modeling today!

More ExcelTips (ribbon)

Digital Signatures for Macros

The security features built into Excel allow you to digitally sign your macros so that users can rest assured that they ...

Discover More

Selecting a Specific Cell in a Macro

Need to use a macro to select a specific cell in a different workbook? It's not as straightforward of a proposition as ...

Discover More

Adjusting Values with Formulas

Paste Special is a great tool that allows you to modify the values in a range of cells in your worksheets. You may want, ...

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 3 + 4?

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.