Visual Basic/VBA – Working With Text Files

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.

 

Method 2

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.

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

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.