MACRO LIBRARY

Error logging using FileSystemObject

Free public access. No account or subscription required.

Files

Error logging using FileSystemObject

Code

Module: mMain

'Demonstrates how to handle error logging in a VBA macro.
    
'Preconditions: Tools-->References contains reference to _
    Microsoft Scripting Runtime.
'Results: Whenever clsLogger.Log is called, whatever text is inputted by the _
    programmer is output to a "logs" folder in the same folder as the macro.
    
'Written by Keith Rice
'CADSharp LLC
'www.cadsharp.com
    
Dim logger As New clsLogger
    
Sub main()
    logger.Log "This is the first line added to the log."
    logger.Log "This is the second line added to the log."
    logger.Log "Finish time: " & Now
End Sub

Class: clsLogger

Dim fso As New FileSystemObject
Dim strLogFilePath As String
    
Private Sub Class_Initialize()
    Dim strMacroPath As String
    strMacroPath = GetMacroFolder
    
    If fso.FolderExists(strMacroPath & "\logs") = False Then
        fso.CreateFolder strMacroPath & "\logs"
    End If
    
    Dim strNow As String
    strNow = Replace(Now, "/", "_")
    strNow = Replace(strNow, ":", "_")
    
    strLogFilePath = strMacroPath & "\logs\" & strNow & ".txt"
    
    fso.CreateTextFile strLogFilePath
        
    Log "Start Time: " & Now
End Sub
    
Public Sub Log(text As String)
    Dim fsoTextStream As TextStream
    Set fsoTextStream = fso.OpenTextFile(strLogFilePath, ForAppending)
    fsoTextStream.WriteLine text
    fsoTextStream.Close
End Sub
    
Private Function GetMacroFolder()
    Dim swApp As SldWorks.SldWorks
    Set swApp = Application.SldWorks
    GetMacroFolder = swApp.GetCurrentMacroPathFolder
End Function