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:
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.
- It exports the entire current worksheet.
- It adds double quotes “” to text values or formatted cells.
So you get this.
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.
Download Save Text example macro
Click here to download the example workbook. Examine 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:
32 Responses to “Save a range as text file using VBA [tutorial]”
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".
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.
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 .....
Print command works for me.
Any how let me check up
Im using the code, but need help on how to print the values with 4 decimals roundup
/Niclas
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.
So good
Awesome code... Is there a way to save the text file in a protected format to prevent editing?
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
If I want tab-delimited output what do I enter instead of the "," in this code?
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.
is it possible to keep the cell format in the output ie. dollar symbol etc?
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
@NAC
Have a read of the solutions at:
https://stackoverflow.com/questions/2524703/save-text-file-utf-8-encoded-with-vba
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.
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"
can you explain about this code for me.
lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
i was not clear about it
Excellent. I could open, save and close file without any problem. Also added different directory to save text file.
Thank you,
' 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
How to text file name is excel cell value
Fantastic solution. Thanks very much for the great tutorial.
Nice vba, just asking how to filter empty rows away from print?
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
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
Whenever i get stuck in Excel, this site is my first port of call 🙂
how do i get rid of the blank line at the end of the output file?
thanks in advance
Hello all,
Love the site.
I'm trying to read the text file back to a worksheet line by line any help welcome
Hey , Thanks for the code. The program is throwing an error when it reaches the line:
Open filename For Output As #1
Please help.
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.
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
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.
Sorry for no line breaks, not sure how to fix that when posting here?
Thanks for your website.