XLA routines: EE_WriteToTextFile

Nick's picture
Similar to logging errors, this simple sub routine writes to a text file
Sub EE_WriteToTextFile(strMsg As String, FilePath As String)
    ' Writing a text file using File System Object in VBA
    ' This code requires a reference (In the VBE Tools > References) to Microsoft Scripting Runtime
    Dim fso         As Object
    Dim FSOFile     As Object
    Dim NoOfLoop    As Integer
 
'http://excelexperts.com/xla-routines-eeWriteToTextFile    for updates on this sub routine

    Set fso = CreateObject("Scripting.FileSystemObject")
    If fso.FileExists(FilePath) = True Then
        Set FSOFile = fso.OpenTextFile(FilePath, 8, True) 'Existing
    ElseIf InStr(FilePath, Application.PathSeparator) > 0 Then
        Set FSOFile = fso.OpenTextFile(FilePath, 2, True) 'Create path with file
    Else
        Set FSOFile = fso.OpenTextFile(Environ("Temp") & Application.PathSeparator & FilePath, 2, True) 'New
    End If
 
    FSOFile.WriteLine (strMsg)
 
    FSOFile.Close
 
    Set fso = Nothing
    Set FSOFile = Nothing
End Sub