How to create and write to a txt file using VBA How to create and write to a txt file using VBA vba vba

How to create and write to a txt file using VBA


Use FSO to create the file and write to it.

Dim fso as ObjectSet fso = CreateObject("Scripting.FileSystemObject")Dim oFile as ObjectSet oFile = FSO.CreateTextFile(strPath)oFile.WriteLine "test" oFile.CloseSet fso = NothingSet oFile = Nothing    

See the documentation here:


Open ThisWorkbook.Path & "\template.txt" For Output As #1Print #1, strContentClose #1

More Information:


To elaborate on Ben's answer:

If you add a reference to Microsoft Scripting Runtime and correctly type the variable fso you can take advantage of autocompletion (Intellisense) and discover the other great features of FileSystemObject.

Here is a complete example module:

Option Explicit' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use' the FileSystemObject which has many useful features for handling files and foldersPublic Sub SaveTextToFile()    Dim filePath As String    filePath = "C:\temp\MyTestFile.txt"    ' The advantage of correctly typing fso as FileSystemObject is to make autocompletion    ' (Intellisense) work, which helps you avoid typos and lets you discover other useful    ' methods of the FileSystemObject    Dim fso As FileSystemObject    Set fso = New FileSystemObject    Dim fileStream As TextStream    ' Here the actual file is created and opened for write access    Set fileStream = fso.CreateTextFile(filePath)    ' Write something to the file    fileStream.WriteLine "something"    ' Close it, so it is not locked anymore    fileStream.Close    ' Here is another great method of the FileSystemObject that checks if a file exists    If fso.FileExists(filePath) Then        MsgBox "Yay! The file was created! :D"    End If    ' Explicitly setting objects to Nothing should not be necessary in most cases, but if    ' you're writing macros for Microsoft Access, you may want to uncomment the following    ' two lines (see https://stackoverflow.com/a/517202/2822719 for details):    'Set fileStream = Nothing    'Set fso = NothingEnd Sub