fbpx
Search
Close this search box.

Save a range as text file using VBA [tutorial]

Share

Facebook
Twitter
LinkedIn

Last night I asked members of our Chandoo.org facebook page to share an Excel problem you are struggling with.  Francis asked,

How to save a file as .txt in vba without quotes? When I save as .txt, the file has got quotes inside of it. I used the code Print, but it didnt work because the file loses its delimitation.
Does anyone know how to solve this?

Let’s understand how to save a range as text and overcome the double quote problem.

Saving a range as Text – the easy way

Say you have a file like this:

save-range-as-text-vba-data

The easy option is to save your worksheet as text file using below macro.



Sub saveText()
    ActiveWorkbook.SaveAs filename:= _
        ThisWorkBook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt", FileFormat:=xlText, _
        CreateBackup:=False
End Sub

While this works, it has 2 problems.

  1. It exports the entire current worksheet.
  2. It adds double quotes “” to text values or formatted cells.

So you get this.

save-as-text-quotation-marks

Saving a range as Text – the proper way

We can create a blank text file using VBA and write the range data values in to that file. This way we will have full control over what goes in to the file and how it’s formatted.

Here is the code:


Sub saveText2()
    Dim filename As String, lineText As String
    Dim myrng As Range, i, j
    
    filename = ThisWorkbook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"
    
    Open filename For Output As #1
    
    Set myrng = Range("data")
    
    For i = 1 To myrng.Rows.Count
        For j = 1 To myrng.Columns.Count
            lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
        Next j
        Print #1, lineText
    Next i
    
    Close #1
End Sub

Let’s understand the code…

Create a file name

We take the current workbook path and set up textfile-time stamp.txt in that directory.

Note, the time stamp portion is dynamic and changes every time you run the code.

We then open the file using Open filename For Output As #1 line.

This sets up a new file and opens it for us to write anything we want.

Loop thru range data and write values to the file

We loop thru each and every cell of the range("data"). We need to take all the values in a row and concatenate them with delimiter comma (,).

This is done in nested for loops (related: Introduction to For loop- Excel VBA)

We loop thru each column in a row and construct lineText.

We then print this lineText to file #1 using,

Print #1, lineText

Finally we close the file.

The end result

This is what we get.

save-as-text-final

Download Save Text example macro

Click here to download the example workbookExamine the savetext macro to learn more.

How do you create text files using VBA?

Do you create text / CSV / TSV files from Excel data? How do you automate the process? Please share your tips and ideas in the comments section.

Learn more powerful ways to use VBA:

Facebook
Twitter
LinkedIn

Share this tip with your colleagues

Excel and Power BI tips - Chandoo.org Newsletter

Get FREE Excel + Power BI Tips

Simple, fun and useful emails, once per week.

Learn & be awesome.

Welcome to Chandoo.org

Thank you so much for visiting. My aim is to make you awesome in Excel & Power BI. I do this by sharing videos, tips, examples and downloads on this website. There are more than 1,000 pages with all things Excel, Power BI, Dashboards & VBA here. Go ahead and spend few minutes to be AWESOME.

Read my storyFREE Excel tips book

Excel School made me great at work.
5/5

– Brenda

Excel formula list - 100+ examples and howto guide for you

From simple to complex, there is a formula for every occasion. Check out the list now.

Calendars, invoices, trackers and much more. All free, fun and fantastic.

Advanced Pivot Table tricks

Power Query, Data model, DAX, Filters, Slicers, Conditional formats and beautiful charts. It's all here.

Still on fence about Power BI? In this getting started guide, learn what is Power BI, how to get it and how to create your first report from scratch.

letter grades from test scores in Excel

How to convert test scores to letter grades in Excel?

We can use Excel’s LOOKUP function to quickly convert exam or test scores to letter grades like A+ or F. In this article, let me explain the process and necessary formulas. I will also share a technique to calculate letter grades from test scores using percentiles.

32 Responses to “Save a range as text file using VBA [tutorial]”

  1. Graham says:

    I export data to an xml file using VBA rather than using the built in Excel "Export to XML" . Using VBA, MSXML and XSLT, the data can then be transformed into other datasets and html pages without the extra HTML tags and styles that are added to a file when using the Excel option of "Save as Web Page".

  2. mark says:

    the double quotes are present only because there are commas in the data. Remove them (for a test) and they are not present. The problem with this solution is that if you really need the commas and you save the text with them, but are not able to differentiate between commas as data and comma as delimiter, the structure of the data is not recoverable. if i were writing a program to read files like this (and i have, often using Rexx), i'd use tabs or commas, accept the quotes, and strip. Still quite easy.

    • Madh says:

      Mark, That was perfect reply, Saved lot of time for me, I was searching for removing double quotes while exporting, Now just changed that "," to "." .. Thatsall!!! Thanks aLot .....

  3. Srinivasan says:

    Print command works for me.
    Any how let me check up

  4. Niclas says:

    Im using the code, but need help on how to print the values with 4 decimals roundup

    /Niclas

    • D.J.C says:

      I create a 'master' power formula column that restructures my data to the exact output that I desire - To achieve 'x' decimals rounded....

      Example Data
      COL'A' COL'B' COL'C' COL'D' COL'E'
      TEST_LINE_03 7.655 7.655 03/03/2017 03/03/2017

      Formula in Column J
      My Numeric Data (COL'C') needs to be rounded to 2 places...

      =""""&A2&""","""&B2&""","&ROUND(C2,2)&","&""""&TEXT(D2,"dd/mm/yyyy")&""","&TEXT(E2,"dd-mmm-yy")

      Output Text
      "TEST_LINE_03","7.655",7.66,"03/03/2017",03-Mar-17

      I need Text to be 'Quoted', while numeric and dates needed to be without quotes.

      Hope this helps, as well as a little extra.

  5. Srinivasan Venkatraman Srinivasan says:

    So good

  6. Havoc says:

    Awesome code... Is there a way to save the text file in a protected format to prevent editing?

  7. Amol says:

    Hello,
    I am trying to write a code for writing excel data (with merged cells)
    to text file.
    I am not able to do it perfectly.
    Please guide me.

    Thanks,
    Amol

  8. minimalist says:

    If I want tab-delimited output what do I enter instead of the "," in this code?

  9. minimalist says:

    I found vbTab as "tab" character.

    Can we modify this code so it uses the current selection of cells as the range to save as text? For example selecting the columns Name and Date of Join and running this code should save only these 2 columns to text:

    Name,Date of Join
    Adam Ackert,13-04-2010

    etc.

  10. beebee says:

    is it possible to keep the cell format in the output ie. dollar symbol etc?

  11. NAC says:

    Thanks a lot for this post! But how can define in VBA that the output file has to be "UTF-8"?. Right now it is being created in ANSI and i have problems with special characters as áí and so on. thanks in advance

  12. Gert says:

    Hi,

    I want to use this as a backup/log textfiles. Is there also a way to place the textfile back into a sheet as text ( no formating ) in VBA ?
    So overwriting the incomplete or missing cells.

    Could not find yet.

  13. Andy says:

    Hi there,

    Is there a way I can get the filename to reference a cell instead of the time and date stamp?

    filename = ThisWorkbook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"

  14. kun says:

    can you explain about this code for me.
    lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
    i was not clear about it

  15. P K Shah says:

    Excellent. I could open, save and close file without any problem. Also added different directory to save text file.
    Thank you,

  16. Harry Edward Sorensen says:

    ' for those who like Arrays
    ' HarryS likes
    Sub GetText3(RaFrom As Range, FileNa$)
    Dim LineText As String
    Dim Ri&, FileNum&, GSA$(), RSA$()

    'Get the file into array
    '
    FileNum = FreeFile()
    Open FileNa For Input As #FileNum
    GSA = Split(Input$(LOF(FileNum), FileNum), vbLf)
    Close #FileNum
    '
    ' put it in range overwriting only its size
    '
    For Ri = 0 To UBound(GSA) - 1 ' 0 based
    RSA = Split(GSA(Ri), ",")
    RaFrom(Ri + 1, 0).Resize(1, UBound(RSA) + 1) = RSA
    Next Ri

    End Sub

    Sub PutText3(Ra As Range, FileNa$)
    Dim LineText As String
    Dim Ri&, CI&, FileNum&, GSA$()
    '
    FileNum = FreeFile()
    Open FileNa For Output As #FileNum ' will make file but not folder
    For Ri = 1 To Ra.Rows.Count
    LineText = vbNullString

    For CI = 1 To Ra.Columns.Count
    LineText = LineText & "," & Ra.Cells(Ri, CI) ' all have , so splits to 0 base
    Next CI
    Print #1, LineText
    Next Ri

    Close #FileNum

    End Sub

  17. B.M.MEGHNATHI says:

    How to text file name is excel cell value

  18. Dan says:

    Fantastic solution. Thanks very much for the great tutorial.

  19. Mike says:

    Nice vba, just asking how to filter empty rows away from print?

  20. Mike says:

    Do anyone know how to save as UTF-8 format?

    Problem is that I have scandinavian letters and ANSI do not support those.

    ---------
    Sub savetoText1()
    Dim FileToSave As String, lineText As String
    Dim myrng As Range, i, j

    FileToSave = ThisWorkbook.Path & "\test" & Format(Now, "yyyymmdd-hhmmss") & ".xml"

    Open FileToSave For Output As #1

    Set myrng = Range("xml!$A:A")

    For i = 1 To myrng.Rows.Count
    For j = 1 To myrng.Columns.Count

    If lineText = IIf(j = 1, "", lineText & " ") & myrng.Cells(i, j) Then
    Close #1
    Exit Sub
    End If

    lineText = IIf(j = 1, "", lineText & " ") & myrng.Cells(i, j)
    Next j
    Print #1, lineText
    Next i
    Close #1
    End Sub

  21. Stephen Spittal says:

    Thank you very much.

    I use this to create a multi user macro enabled Excel workbook.

    My issue is that i have now had to move all the shared text files to sharepoint and i need to be able to check it in after creating the file can anyone help

  22. Jack Griffin says:

    Whenever i get stuck in Excel, this site is my first port of call 🙂

  23. do do says:

    how do i get rid of the blank line at the end of the output file?

    thanks in advance

  24. Steohen says:

    Hello all,
    Love the site.
    I'm trying to read the text file back to a worksheet line by line any help welcome

  25. Ritu says:

    Hey , Thanks for the code. The program is throwing an error when it reaches the line:
    Open filename For Output As #1

    Please help.

    • Chandoo says:

      Hi Ritu...

      This program tries to save the file in current workbook folder. So make sure you can actually save files there. Try by first saving the Excel file to a regular folder like desktop or mydocuments. Let me know if you still have a problem.

  26. Paresh says:

    Hello Chandu,

    I've Understood what you've done above with your Code, but I am Stuck with my Excel Spreadsheet.

    I need your Assistance, with Converting Excel data into CSV or TXT Format as follows:

    0001,5002,,,45.00,,,N
    0001,5321,,,4.00,,,N
    0001,5323,,,2.00,,,N
    0002,5002,,,45.00,,,N
    0002,5321,,,3.00,,,N
    0002,5323,,,0.00,,,N

    Please let me know if Possible.

    I can send you the Excel Spreadsheet if you like.

    I will await your Response

  27. Keith A Swerling says:

    When using the text file writing method I noticed that when I had a file that was 3,000 lines in length, XL would take a few minutes to write the text file. You can name the text file with any extension, in my case I needed a ".bat" file.

    I use this method and it only takes a second to output the file:

    Sub OutputTextFile()

    Sheets("sheet1").Select
    Sheets("sheet1").Copy

    ActiveWorkbook.SaveAs FileName:= _
    "C:\TextFile.txt", FileFormat:=xlTextPrinter, _
    CreateBackup:=False

    End Sub

    Hopefully that helps someone someday.

    • Keith A Swerling says:

      Sorry for no line breaks, not sure how to fix that when posting here?

      Thanks for your website.

Leave a Reply