VBA Open Text Files

VBA Open Text Files

VBA Open Text Files using OpenTextFile method of file system object Let us see example 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

VBA Open a Text File in Output Mode

Here is an example to open a Text File in Output Mode.

'VBA Open Text Files in Excel
Sub VBAF1_Open_TextFile()
    'Variable declaration
    Dim sFile As String
    Dim ifileNumber As Integer
    'Specify text file path to open
    sFile = "C:\VBAF1\FirstTextFile.txt"
    'Assign a unique file number
    fileNumber = FreeFile
    'Open text file in output mode
    Open sFile For Output As #fileNumber
End Sub

VBA Open Text File in Notepad for Reading

You can find following example to Open Text File for Reading using Excel VBA. Here we use VBA OpenTextFile method of File system object to open text file.

'VBA OpenTextFile for Reading
Sub VBAF1_To_Open_TextFile_For_Reading()
    Dim oFSO As New Filesystemobject
    Dim sFile As String
    Dim myTextStream As TextStream
    'Specify text file path to open
    sFile = "C:\VBAF1\FirstTextFile.txt"
    'Open text file to read
    Set myTextStream = oFSO.OpenTextFile(sFile, ForReading, False, TristateFalse)
    'Print text file data in immediate window
    Debug.Print myTextStream.ReadLine
    'Close opened text file.
End Sub

Output: Here is screenshot for your reference. You can see output in the immediate window.

VBA OpenTextFile
VBA OpenTextFile

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

Leave a Comment