fbpx

Save a range as text file using VBA [tutorial]

Share

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
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:

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
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

Chandoo is an awesome teacher
5/5

– Jason

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

100 Excel Formulas List

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

20 Excel Templates

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

IRR and data tables in Excel

Using IRR with Data Tables – Modeling Cash-flow Scenarios in Excel

Do you want to simulate multiple cash-flow scenarios and calculate the rate of return? Then this article is for you. In this page, learn how to,

  • Introduction to IRR & XIRR functions
  • Calculate rate of return from a set of cash-flows with XIRR
  • Simulating purchase or terminal value changes with data tables
  • Apply conditional formatting to visualize the outputs
  • Common issues and challenges faced when using XIRR

24 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

Leave a Reply