If you browse your Program files folder in windows almost every program will have some text files for storing some configurations or logs etc. stored in it.
Did you Know?
XML Files are also text files. The only difference is that XML files are more structured than Text files. This is the reason XMLs are widely used for communication.
In this article I am going to teach you in detail – How to deal with Text Files in Excel VBA. As explained above, Text files are very useful while developing any tool or add-in in Excel where you want to store some configuration data – in order to run your program or add-in. Using Excel file to store such data will make the program very slow.
I don’t need to explain much – about why a Text file would be a better option, rather you will find it by yourself at the end of this article.
So let’s start then in a logical order… Opening a file… reading a file… writing into a file.. etc.
Topics covered in this Article
In this article, the following topics are covered. Click on the below links to directly jump to that section
1. Excel VBA to Open a Text File
2. Excel VBA to create a NEW Text File
3. VBA to write a Text file using Write Statement
4. VBA to write a Text file using Print Statement
5. VBA to Append to a Text File
5. What is FreeFile () function ?
How to read a file, will be covered in the next article.
Excel VBA Code to Open a Text File
Following is the code Syntax to open a Text file:
Open [file Path] For [mode] As [#FileNumber]
With the Above code Syntax, as you can see, there are 3 parameters. [file Path] [mode] and [#FileNumber]
So, lets discuss about these three parameters – who are they and what role do they play in opening the text file:
What is File Name
This is the path of the Text file which is going to be opened.
What is Mode in Open Text File VBA Code
As the name suggests, its the control which you want to specify before opening it. There are mainly 3 types of controls or modes possible – Input, Output and Append.
Lets discuss one by one these 3 modes
Input Mode
This mode is used for READ ONLY control. It means, if you open a Text file in Input mode, then you can not write anything in it. All you can do is – read all the content inside the text file. Therefore you can say.. this a read only mode.
Output Mode
If your text file is open in this mode, then you can write content in it. But what is important here to note is : In this mode, your existing file gets overwritten. This means, if there are content already in there in the text file then it will be replaced by the new data which you are trying to save. Therefore, be careful while choosing the mode of the file while opening it.
Now you must be thinking – Then how to append content in an existing text file without overwriting it. Therefore the next mode – Append Mode.
Append Mode
As the name suggests, this mode allow you to append the new content at the end of the text file. It does not overwrite the existing content in the text file.
So now we have an idea about all these 3 modes. It will be more clear when we use them in the below examples.
Now Let’s learn about our second parameter – #FileNumber
#FileNumber
When Text files are opened then windows recognize them by a unique integer value. Valid range of Integers for this parameter is between 1 to 511.
As I mentioned above, it should be a unique integer, it is challenging for you to give a fixed number here in case you are dealing with multiple text files. To overcome this challenge you can use a function called FreeFile()
What is FreeFile() Function?
FreeFile() function returns a unique integer value which represents the file number of the file you opened. This way always a unique (or a FREE File Number – which is not used already) file-Number is assigned automatically by this function.
Now you know about – How to open a Text file. Let’s see some examples and learn how to use it.
Sample VBA Code to Open a Text File
Sub OpenTextFile()
Dim sFilePath As String
Dim fileNumber As Integer
' Full path of the textFile which you want
' to open.
sFilePath = "C:\Users\Vishwa\Desktop\LEM.txt"
' Assign a unique file numner
fileNumber = FreeFile
' Below statement will open the
' above text file in output mode
Open sFilePath For Output As #fileNumber
End Sub
VBA code to create a new TextFile
If the file name provided in the File Path provided while writing Open statement, like above, does not exists, then Open statement, automatically creates a TextFile with the same name in the same directory.
Thus, using the same Open statement, you can create a new TextFile as well. You don’t have to use a different statement to create a new file.
Here is a sample code
Read the commented lines written inside the code. I have tried explaining them there as well.
Sub createANewtextFile()
Dim sFilePath As String
Dim fileNumber As Integer
' In the above path C:\Users\Vishwa\Desktop\ - exists
' But on the desktop - LEM.txt file does not exist
sFilePath = "C:\Users\Vishwa\Desktop\LEM.txt"
' Assign a unique file numner
fileNumber = FreeFile
' in this case, below statement, will
' create a new file with name LEM.txt
' as soon as below statement gets executed
' And also, it is open to write something
Open sFilePath For Output As #fileNumber
End Sub
Note: Only File Name should not exists in order to create a new file. Directories or folders specified must exists. If not, file Not Found Error will be thrown.[/fusion_text]
VBA Code to Write content in to Text File
[fusion_text]Basically there are two statements using which you can write content in to a text file in excel VBA : Write or Print[/fusion_text][title size=”1″ content_align=”left” style_type=”none” sep_color=”” margin_top=”” margin_bottom=”” class=”” id=””]VBA to write in to Text Files using Write statement[/title][fusion_text]As I mentioned above, one can write in to text files using two statements Write or Print. First lets have a look on – how to write content in to a text file using Write statement.[/fusion_text]
Write #<fileNumber>, InputData 1, InputData 2, ….
[title size=”2″ content_align=”left” style_type=”none” sep_color=”” margin_top=”” margin_bottom=”” class=”” id=””]Where:[/title][fusion_text]
File Number : This is a nemeric value which represents the File. This must be a unique number assigned to each open text files. Text files are identified by these unique numbers assigned to them while opening them. refer the Open File statement to know more about FileNumber
Input Data1, 2, 3, …:
This is the data which you want to write in the Textfile. You can write many different kind of data in each line. Each of these data will be written in textfile in a single line separated by comma.
Important to note:
Based on the type of the data which you put in InputData 1, 2 etc. Write statement does some common changes while putting them in to TextFile.
If the data is Date Type: Then date value is closed within hash sign. Date – 2010-10-13 will be written in TextFile as #2010-10-13#
String type data: They are stored in double quotes. For example : Input Data – Vishwamitra Mishra will be stored as “Vishwamitra Mishra”.
Integer, Double, Long etc : They will be written as they are. There is not formatting done before they are written in text file.
Example:
Let’s take an example. Export the following table in excel to a Text file using Write statement.
From the above excel cells, I will start reading one by one every column values of each row and write them in Text File.
VBA Code – To Write Text File – using Write Statement
Sub WriteTextFileUsingWriteStatement()
Dim sFilePath As String
Dim iRow As Integer
Dim OrderDate As Date
Dim OrderPriority As String
Dim OrderQuantity As Integer
Dim Discount As Double
Dim ShipMode As String
Dim CustomerName As String
Dim ShipDate As Date
iRow = 2
sFilePath = "C:\Users\Vishwa\Desktop\LEM.txt"
' unique file number to access the file uniquely
fileNumber = FreeFile
' to check if file name LEM.txt exists
' if not, end the program
If (VBA.Len(VBA.Dir(sFilePath))) = 0 Then MsgBox "File Does not exists": End
' Open the TextFile in Output mode
' in order to write in something
Open sFilePath For Output As #fileNumber
' Loop to read one by one every
' non empty row and write them
' in the text file
Do
With Sheets("Orders")
OrderDate = .Cells(iRow, 1).Value
OrderPriority = .Cells(iRow, 2).Value
OrderQuantity = .Cells(iRow, 3).Value
Discount = .Cells(iRow, 4).Value
ShipMode = .Cells(iRow, 5).Value
CustomerName = .Cells(iRow, 6).Value
ShipDate = .Cells(iRow, 7).Value
End With
' Now write these data in text file in next line
Write #fileNumber, OrderDate, OrderPriority, OrderQuantity, Discount, ShipMode, ShipDate
' go to the next row in Excel sheet
iRow = iRow + 1
Loop Until IsEmpty(Sheets("Orders").Cells(iRow, 1).Value)
' Close the file once all data
' is written in text file
Close #fileNumber
End Sub
Result : after Running the above code
After running the above code, Your text file will look something like this:
Now you can see, as explained above, dates are put under Hash marks (#) and string data is put under double quotes (” “).
Important points to note in above code:
1. I have used Dir$ function to check if TextFile already exists. Why I am thinking it is important to mention is because, if you do not put this check and by mistake your file name is not correct, then Open File statement will create a new TextFile in the same location with your provided name and write the content in that new file.
Note: Open file statement will create a new file only if directory exists. If directory itself does not exists, then Open File statement will through an error – Path Not found.
It will not create a directory in that case.
2. Instead of using a fixed number like #1, #2 etc. for FileNumber, I have used the function FreeFile() which always finds an available fileNumber which can be assigned to a textFile. It is always a good practise to use this function rather using a hardcoded File Number. This becomes very important when your program start dealing with multiple text files.
3. To read every line from Excel and write it in textFile, I have used Do..While loop with Until keyword for condition. You can read more about do.. while loop and Until keyword here.
4. Last but not the least – do not forget the Close the file by using the same fileNumber by using the simple statement Close #FileNumber as you can see in the above code.
How to write TextFile using Print Statement
Syntax remains exactly same as Write statement. Main difference between Write and Print statement is in the formatting of the Output in TextFile. You will see in detail. Let’s start with the Syntax:
Syntax of Print statement:
Print #<FileNumber>, InputData1, InputData2, ….
Where:
File Number : This is a numeric value which represents the File. It is exactly same as explained above in Write Statement.
Input Data 1, 2, 3, …:
This is the data which you want to write in the Textfile. You can write many different kind of data in each line. Each of these data will be written in textfile in a Proper formatting with proper spacing. TextFile which you get from Print statement is well formatted for printing purposes. That means spaces between columns are adjusted based on the values in those columns. You will see in the example below.
Important to note:
Unlike Write statement, this does not change any of the formatting of the data for Date or String type. It just put them as they are.
Values of difference columns are not separated by Comma. Rather they are separated by space(s) depending on how many spaces required to make the textfile in a printable format.
Example: To write Text File using PRINT Statement
Let’s take the same example as above. Now we will export the same table from excel to a Text file using Print statement.
Here is the code
Sub WriteTextFileUsingPrintStatement()
Dim sFilePath As String
Dim iRow As Integer
Dim OrderDate As Date
Dim OrderPriority As String
Dim OrderQuantity As Integer
Dim Discount As Double
Dim ShipMode As String
Dim CustomerName As String
Dim ShipDate As Date
iRow = 2
sFilePath = "C:\Users\Vishwa\Desktop\LEM.txt"
' unique file number to access the file uniquely
fileNumber = FreeFile
' to check if file name LEM.txt exists
' if not, end the program
If (VBA.Len(VBA.Dir(sFilePath))) = 0 Then MsgBox "File Does not exists": End
' Open the TextFile in Output mode
' in order to write in something
Open sFilePath For Output As #fileNumber
' Loop to read one by one every
' non empty row and write them
' in the text file
Do
With Sheets("Orders")
OrderDate = .Cells(iRow, 1).Value
OrderPriority = .Cells(iRow, 2).Value
OrderQuantity = .Cells(iRow, 3).Value
Discount = .Cells(iRow, 4).Value
ShipMode = .Cells(iRow, 5).Value
CustomerName = .Cells(iRow, 6).Value
ShipDate = .Cells(iRow, 7).Value
End With
' Now write these data in text file in next line
Print #fileNumber, OrderDate, OrderPriority, OrderQuantity, Discount, ShipMode, ShipDate
' go to the next row in Excel sheet
iRow = iRow + 1
Loop Until IsEmpty(Sheets("Orders").Cells(iRow, 1).Value)
' Close the file once all data
' is written in text file
Close #fileNumber
End Sub
Result : after Running the above code
After running the above code, Your text file will look something like this:
Now you can see, as explained above:
1. None of the data are formatted. They are, in fact, put as they are in Excel cells.
2. Spaces between columns are adjusted based on the data in each columns.
Important to know…
There is another – in fact important – difference between Write and Print statement. That you will realize while reading above two TextFiles –
1. Written using Write Statement
2. Written using Print Statement. This is a hint for now. It will be explained in detail in the next article, where we will be talking all about reading a TextFile.
[/fusion_text][fusion_text]In all the above examples of writing to a text box, I have used the File Open mode as Output. This means, every time you run the code, all the content of the text file will be replaced with the new one. Therefore, let’s take an example, of how can we append to the existing content in a text file using write or print statement.
VBA Code to Append to Text File
The whole trick lies in to the mode you open your text file during your VBA program. Why I say that, because you do not need to change anything else in the Write or Print statements in order to append and not to replace. Isn’t it simple? So the complete VBA code remains same as it is there for replacing the whole content – except changing the open mode – from Output to Append. What these modes are – They are explained in the beginning of the article.
Sub AppendToTextFile()
Dim sFilePath As String
Dim iRow As Integer
Dim OrderDate As Date
Dim OrderPriority As String
Dim OrderQuantity As Integer
Dim Discount As Double
Dim ShipMode As String
Dim CustomerName As String
Dim ShipDate As Date
iRow = 2
sFilePath = "C:\Users\Vishwa\Desktop\LEM.txt"
' unique file number to access the file uniquely
fileNumber = FreeFile
' to check if file name LEM.txt exists
' if not, end the program
If (VBA.Len(VBA.Dir(sFilePath))) = 0 Then MsgBox "File Does not exists": End
' Open the TextFile in Append mode
' in order to write in something
Open sFilePath For Append As #fileNumber
' Loop to read one by one every
' non empty row and write them
' in the text file
Do
With Sheets("Orders")
OrderDate = .Cells(iRow, 1).Value
OrderPriority = .Cells(iRow, 2).Value
OrderQuantity = .Cells(iRow, 3).Value
Discount = .Cells(iRow, 4).Value
ShipMode = .Cells(iRow, 5).Value
CustomerName = .Cells(iRow, 6).Value
ShipDate = .Cells(iRow, 7).Value
End With
' Now write these data in text file in next line
Write #fileNumber, OrderDate, OrderPriority, OrderQuantity, Discount, ShipMode, ShipDate
' go to the next row in Excel sheet
iRow = iRow + 1
Loop Until IsEmpty(Sheets("Orders").Cells(iRow, 1).Value)
' Close the file once all data
' is written in text file
Close #fileNumber
End Sub
Note: All the new information gets appended at the end of the text file (from the first blank line)
Did you like this article? Then share it with your friends… spread knowledge…”
Learn All about interacting with Text Files in Excel VBA like opening, creating, writing, reading etc. from Text Files using Excel VBA code”
Useful good content! I need to copy the whole cell content ie I have the cell B2 that contains “0072533944” I need to include the 00 when printing to the txt file and if the cells does not have content I need to include the empty spaces that cells contains