Here are a few methods for reading/writing text files.
Note: These bits of code are mostly for my own reference, but if anyone else finds them useful all the better.
Method 1 – This only works with VB, it doesn’t work with VBA.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
Sub WorkingWithTextFiles_Method1() Dim PathString As String Dim Filename As String Dim FullPath As String Dim DataString As String Dim AppendStatus As Boolean Dim InputTextFile As StreamReader Dim OutputTextFile As StreamWriter Filename = "myfile.txt" PathString = "D:\Fooj\" FullPath = PathString + Filename DataString = "The quick brown fox jumped over the lazy dog." ' Determine if we will append or not If (My.Computer.FileSystem.FileExists(FullPath)) Then ' The file exists, so open it in append mode AppendStatus = True Else ' The file doesn't exist, so open it in non-append mode AppendStatus = False End If ' Create/open the file, write a line then close the file OutputTextFile = My.Computer.FileSystem.OpenTextFileWriter(FullPath, AppendStatus) OutputTextFile.WriteLine(DataString) OutputTextFile.Close() If (My.Computer.FileSystem.FileExists(FullPath)) Then ' Open the file, read a line then close the file InputTextFile = My.Computer.FileSystem.OpenTextFileReader(FullPath) DataString = InputTextFile.ReadLine InputTextFile.Close() End If End Sub |
Method 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
Sub WorkingWithTextFiles_Method2() ' Add a reference to "Microsoft Scripting Runtime" Dim CurrentFileSystemObject As New FileSystemObject Dim CurrentTextFile As TextStream Dim PathString As String Dim Filename As String Dim FullPath As String Dim DataString As String Filename = "myfile.txt" PathString = "D:\Fooj\" FullPath = PathString + Filename DataString = "The quick brown fox jumped over the lazy dog." If (CurrentFileSystemObject.FileExists(FullPath)) Then ' Open the file, read a line then close the file Set CurrentTextFile = CurrentFileSystemObject.OpenTextFile(FullPath) DataString = CurrentTextFile.ReadLine CurrentTextFile.Close Else ' Create the file, write a line then close the file Set CurrentTextFile = CurrentFileSystemObject.CreateTextFile(FullPath) CurrentTextFile.WriteLine (DataString) CurrentTextFile.Close End If End Sub |
Method 3 – This may only work with VBA now.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
Sub WorkingWithTextFiles_Method3() Dim PathString As String Dim Filename As String Dim FullPath As String Dim DataString As String Filename = "myfile.txt" PathString = "D:\Fooj\" FullPath = PathString + Filename DataString = "The quick brown fox jumped over the lazy dog." ' Open/Create the file, write a line then close the file Open FullPath For Output As #1 Write #1, DataString Close #1 ' Open the file, read a line then close the file Open FullPath For Input As #1 Input #1, DataString Close #1 End Sub |