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.
Please click on following link to know about how to add reference of Microsoft scripting Runtime.
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
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
You can refer the following link for the step by step instructions.
Click on the following links of the useful resources. These helps to learn and gain more knowledge.