VBA Create Text Files

VBA Create Text File

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.

VBA Create Text File
VBA Create Text File

Instructions to use Macro

Here are the instructions to use above macro in Visual basic editor.

  • Open Visual Basic Editor(VBE) by clicking Alt +F11
  • Go to code window by clicking F7
  • Copy above specified macro or procedure
  • Paste above copied code in code window
  • Run macro by clicking F5 or Run command
  • You can see output in the immediate window
  • you can find above specified input and output screenshot for your reference and better understand.

Related Articles

You can also learn complete details like syntax, example and etc.

VBA Text Files Complete Reference Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *