VBA Open Text Files using OpenTextFile method of file system object Let us see example in the following tutorial.
Please click on following link to know about how to add reference of Microsoft scripting Runtime.
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
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() 'Variabledeclaration 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. myTextStream.Close End Sub
Output: Here is screenshot for your reference.
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.
You can also learn complete details like syntax, example and etc.