VBA Create Text File using CreateTextFile method of file system object (FSO) and Text Files Open statement. let us see both methods in the following tutorial.
Add Reference: Microsoft scripting Runtime
Please click on following link to know about how to add reference of Microsoft scripting Runtime.
Create Microsoft Scripting Runtime Library Reference
Example to Create Text File using FSOin Excel VBA
Let’s see following example to create Text File for writing using Excel VBA. Here we use VBA CreateTextFile method of File system object to create text file.
'VBA CreateTextFile Sub sb_VBA_To_Create_TextFile() 'Variabledeclaration Dim oFSO As New Filesystemobject Dim sFile As String Dim myTextStream As TextStream 'Specify text file path to open sFile = "C:\VBAF1\CreateTextFile.txt" 'Create text file to Write Set myTextStream = oFSO.CreateTextFile(sFile, True) 'Write to text file myTextStream.WriteLine "Test File." 'Close opened text file. myTextStream.Close End Sub
Example to Create Text File in Excel VBA
Let us see another example to Create Text File using Open statement in Excel VBA.
'VBA Create Text File Sub VBAF1_To_Create_TextFile_Using_Open_Statement() 'Variable declaration Dim FileNum As Integer Dim sFile As String 'Specify text file path to open sFile = "C:\VBAF1\CreateTextFile.txt" 'Specify the next available file number FileNum = FreeFile 'Open the text file Open sFile For Output As FileNum 'Close Text File Close TextFile End Sub
Here is the output screen shot for your reference. You can see output in the immediate window
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays VBA Text Files VBA Tables
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog