Return to VBA Code Examples

VBA – Write to Text File

This tutorial will demonstrate how to write to text files using VBA.

Write to a Text File

The below codes use the FileSystemObject (learn more). In order to use it, you will need to set a reference to the VB script run-time library.

Write to New Text File

With the CreateTextFile method of FileSystemObject you can create and then add content to a text file:

Please note that content will not be enclosed by quotes.

Write to Existing Text File

To write to an existing text file you can use the OpenTextFile method of FileSystemObject with ForWriting mode.

Please note that you do not necessarily need FileSystemObject to write to an existing text file. The above example is shown in another way in this code below (see other example in the Data Range to Text File section):

Please note that using Write command instead of Print will result in having the added content enclosed by quotes. Having both commands in your macro

will result in a text file like this:

text in quotes

Append to Text File

By changing the mode in the above code to ForAppending, a line can be added to the end of the text file:

WriteLine Method

This method appends the input string as a separate line to the existing content.

Write Method

The input string is appended on the same line as the existing content.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! automacro

Learn More!!


This method takes the number of blank lines to be written to the text file as a parameter.

This code below illustrates the difference between the different write methods:

And the result:write methods

Data Range to Text File

If you want to output a data range from your worksheet to a text file, you can use this code:

Array to Text File

You can also save your array of data into a text file like this: