Return to VBA Code Examples

VBA – Create Text File with CreateTextFile

This tutorial will demonstrate how to create a text file with VBA.

Create a Text File

This lesson uses the FileSystemObject. In order to use it, you will need to set a reference to the VB script run-time library.

To create a text file, you can use this code below with CreateTextFile Method.

Sub FSOCreateTextFile()
    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Dim TextFile As Object

    Set TextFile = FSO.CreateTextFile("C:\Test\TestFile.txt")

End Sub

You can pass optional arguments to the CreateTextFile method:

  • If you set the “overwrite” argument to true, an already existing file can also be overwritten.
  • Setting the “unicode” argument true, a unicode file is created, otherwise (or if the argument is omitted) the result will be an ASCII file.

In the following example, an existing TestFile.txt will be overwritten with a unicode file:

Set TextFile = FSO.CreateTextFile("C:\Test\TestFile.txt", True, True)

Writing to Text File

After creating a text file you can write text to the file using a single line of code:

TextFile.Write "content"

Click the link to learn more about writing to text files using Write, WriteLine, WriteBlankLines methods.

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! vba save as


Learn More!