Wednesday 31 August 2011

Creating and reading data from text files

It is sometimes useful to keep data in a text file.  For example one of our clients has a resource file which has onOpen and onClose routines that log the current user, the date and time and whether the file was opened read/write or read only.

The code below shows how this can be done.

Sub Create_A_File()
' Put data into a text file
' This routine will create the file if it does not already exist

    Dim strMsg  As String
    Dim strFile As String

    strFile = ThisWorkbook.Path & "myFile.txt"
    ' could be .doc, .txt, .log etc

    strMsg = "Some text could go here"

    ' Open file for output - clears any current data
    'Open strFile For Output As #1
    ' or Open file for append - updates any current data
    Open strFile For Append As #1

    Print #1,                       ' Print blank line to file.
    Print #1, "*****"               ' Print ***** line to file.
    Print #1, strMsg                ' Print a variables value to the text file
    Print #1, Now, strMsg           ' Print date/time and the message, using commas create tab seperated data
    Print #1,                       ' Print another blank line to file.
    Print #1, Application.UserName  ' Print the current user's Excel username
    Print #1, Now                   ' Print the date and time

    Close #1                        ' Close file.

End Sub

Sub GetFromTxt()
' Copy data from one text file to another

    Dim FilePath    As String
    Dim File1       As String
    Dim File2       As String
    Dim File3       As String
    Dim FileData    As String

    Const FileExt   As String = ".txt"

    FilePath = "C:\File\Path\"
    File1 = "File Name 1"
    File2 = "File Name 2"
    File3 = "File Name 3"

    ' Example: FilePath & File1 & FileExt = "C:\File\Path\File Name 1.txt"

    'Open all relevant files
    Open FilePath & File1 & FileExt For Output As #1
    Open FilePath & File2 & FileExt For Input As #2
    Open FilePath & File3 & FileExt For Input As #3

    'Copy each line of the first existing file into the
    'new combined file
    Do While Not EOF(2)
        Input #2, FileData
        Print #1, FileData
    Loop

    'Copy each line of the second existing file into the
    'new combined file
    Do While Not EOF(3)
        Input #3, FileData
        Print #1, FileData
    Loop

    'Close all files
    Close #1
    Close #2
    Close #3
End Sub

Hope that proves useful.

No comments:

Post a Comment

Please, no purely anonymous comments, they will be deleted; always use a name for ease of reference by other commenters.