VBA – Append Text to a Text File

Ever simply wanted to append data into an existing text file? The procedure below does exactly that. Simply supply the full path and file name of the text file to append to, and supply the string to append and voila!

'---------------------------------------------------------------------------------------
' Procedure : Txt_Append
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Output Data to an external file (*.txt or other format)
'               If the file does not exist already it will be created automatically
'               ***Do not forget about access' DoCmd.OutputTo Method for
'               exporting objects (queries, report,...)***
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFile     : Name of the file that the text is to be output to including the full path
' sText     : Text to be output to the file
'
' Usage:
' ~~~~~~
' Call Txt_Append("C:\temp\text.txt", "This is a new appended line of text.")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2011-06-16              Initial Public Release
' 2         2018-02-24              Updated Copyright
'                                   Updated error handler
'---------------------------------------------------------------------------------------
Function Txt_Append(sFile As String, sText As String)
    On Error GoTo Err_Handler
    Dim iFileNumber           As Integer

    iFileNumber = FreeFile                   ' Get unused file number
    Open sFile For Append As #iFileNumber    ' Connect to the file
    Print #iFileNumber, sText                ' Append our string
    Close #iFileNumber                       ' Close the file

Exit_Err_Handler:
    Exit Function

Err_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: Txt_Append" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    GoTo Exit_Err_Handler
End Function

One response on “VBA – Append Text to a Text File