Created
October 23, 2017 13:41
-
-
Save danielleevandenbosch/6a9d744d7e70939d60375c7faa9213f4 to your computer and use it in GitHub Desktop.
error logging in vba
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'code author: Daniel Van Den Bosch | |
'copyright 2017 | |
'CC-BY | |
'paste this code into a new module and replace all MsgBox code with Lmsgbox | |
'this will log all the message boxes to a text file on hte users c drive under | |
'C:\db_objects\error_logs\ with the application name. | |
'this will allow you to support the application should the end user run into issues. | |
'used with good error handling, it will allow you to see the error messages the end user gets. | |
'tested and works in ms-access | |
Public Sub LogError(strError) | |
Const ForAppending = 8 | |
Dim strPath As String | |
Dim fs As Object | |
Dim a As Object | |
run_batch_script ("mkdir C:\db_objects\" & vbCrLf & "mkdir C:\db_objects\error_logs\") | |
strPath = "C:\db_objects\error_logs\" | |
Set fs = CreateObject("Scripting.FileSystemObject") | |
If fs.FileExists(strPath & "\" & Replace(Application.CurrentProject.Name, ".", "_dot_") & "ErrorLog.txt") = True Then | |
Set a = fs.OpenTextFile(strPath & "\" & Replace(Application.CurrentProject.Name, ".", "_dot_") & "ErrorLog.txt", ForAppending) | |
Else | |
Set a = fs.createtextfile(strPath & "\" & Replace(Application.CurrentProject.Name, ".", "_dot_") & "ErrorLog.txt") | |
End If | |
a.WriteLine Date + Time & " " & strError | |
a.Close | |
Set fs = Nothing | |
End Sub | |
Public Function run_batch_script(the_batch_contents As String) | |
On Error GoTo proc_err | |
Dim batchContents As String | |
Dim batchFile As String | |
Dim FF As Byte | |
batchFile = Environ$("USERPROFILE") & "\" & Int((100 - 1 + 1) * Rnd + 1) & "temp.bat" | |
batchContents = "color 99" & vbCrLf & "mode con: cols=20 lines=1" & vbCrLf & the_batch_contents | |
FF = FreeFile | |
Open batchFile For Output As #FF | |
Print #FF, batchContents | |
Close #FF | |
CreateObject("WScript.Shell").Run batchFile, 1, True | |
DoEvents | |
Kill batchFile | |
Exit Function | |
proc_err: | |
MsgBox "there was an issue. try again", vbCritical, "batch file error" ' left alone to aviod infinate loops | |
End Function | |
Public Function Lmsgbox(lprompt As String _ | |
, Optional lbuttons As VbMsgBoxStyle _ | |
, Optional ltitle As String = "vba") As Integer | |
Lmsgbox = MsgBox(lprompt, lbuttons, ltitle) | |
Call LogError("MsgBox " & lprompt) | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment