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. 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.