The FileSystemObject VBA CreateTextFile creates a text file and returns a TextSteam object that allows you to read and write to the file.
VBA FileSystemObject Methods
- BuildPath
- CopyFile
- CopyFolder
- CreateFolder
- CreateTextFile
- DeleteFile
- DeleteFolder
- DriveExists
- FileExists
- FolderExists
- GetAbsolutePathName
- GetBaseName
- GetDrive
- GetDriveName
- GetExtensionName
- GetFile
- GetFileName
- GetFolder
- GetParentFolderName
- GetSpecialFolder
- GetTempName
- MoveFile
- MoveFolder
- OpenTextFile
VBA CreateTextFile Syntax
fso.CreateTextFile (filename, [ overwrite, [ unicode ]])
filename
Name of the file to create. Be sure to add .txt extension to be able to open in text editor by default.
overwrite
Optional. If True will overwrite a file with same name.
unicode
Optional. If True then Unicode file will be created. If False then ASCII. By default ASCII file is created.
VBA CreateTextFile Examples
Write a line to text file with New Line (late binding)
Dim fso as Object, ts as Object 'Create the FileSystemObject Set fso = CreateObject("Scripting.FileSystemObject") 'Create the TextStream Set ts = fso.CreateTextFile("C:\hello.txt") 'Write 2 lines ending with New Line character to text file ts.WriteLine "Hello World!" ts.WriteLine "Hello People!" 'Close the file ts.Close 'Clean up memory Set fso = Nothing Set ts = Nothing
This is the result:
Hello World! Hello People!
Write a string to text file w/o new line (early binding)
Below a different procedure this time with Early Binding and writing a string without a New Line character at the end.
Dim fso as FileSystemObject, ts as TextStream 'Create the FileSystemObject Set fso = New FileSystemObject 'Create the TextStream Set ts = fso.CreateTextFile("C:\hello.txt") 'Write a line ending with NewLine to text file ts.Write "Hello World!" ts.Write "Hello People!" 'Close the file ts.Close 'Clean up memory Set fso = Nothing Set ts = Nothing
This is the result:
Hello World!Hello People!