nVision Error Handling – Write to the Windows Event Log

Wouldn’t it be great to be able to write to a log file that is centrally located, is standard, and built inside of Windows?

Why not write to the system event log? First – DON”T use this suggestion available from Microsoft.  It’s actually horrid looking.  Read it to appreciate where I’m going to be leading you to below.

Old school VB and now VBA create and then use COM object references.  So here we are going to create an object referencing the Windows Scripting libraries.  WSH is getting old but is still inside the current operating systems (Windows 2008 and Windows 7).

MS Technet has a nice outline here on Windows Scripting – the link directs you to an article on writing to the event logs.

Let’s do one better – here is all you need to write to the event log:

Dim WshShell As Object

Set WshShell = CreateObject(“WScript.Shell”)
WshShell.LogEvent
 , Set WshShell = Nothing

That is it.  When your code does write to the event log, it will be available in the Windows Application Logs, and the Source will be WSH.

I created a module way back in about 2002 that I bring into all my nVision programs.  There are two parts to it – an enumerated type that is used to send an optional icon type; and the function that writes to the event  log.

I have a link to a Word document with the code in it here.

For the other part – here is how to throw errors that will get written to the event log.

VBA does not allow the more modern try … catch type of error handling – you declare your error handling procedure in a GoTo statement (this carries over from older BASIC).  Your error declaration becomes:

On Error GoTo Error_Handler

So in a subroutine or function you would write this as:

Private Function doSomeWork( ByRef foo as VariableType)

On Error GoTo Error_Handler

Dim ErrorHeader As String

ErrorHeader = “Oops, a bad thing happened here”

Exit Function

Error_Handler:

Dim strErrorMessage As String  

strErrorMessage = strErrorMessage & ”  Error Source: ” & Err.Source & “.  ”
strErrorMessage = strErrorMessage & “Error #” & Err.Number & ” – ”
strErrorMessage = strErrorMessage & “Description: ” & Err.Description & “.  ”
strErrorMessage = strErrorMessage & “VBA Help Message # ” & Err.HelpContext & “.  ”
strErrorMessage = strErrorMessage & “DLL Error: ” & Err.LastDllError & “.  ”
WriteErrorLogEntry ErrorHeader & strErrorMessage

End Function

You can of course get a lot more creative than this – when I was recently debugging macro code during our conversion to Office 2007 on a 64 bit Windows 2008 machine – I wrote to the event log at several points in functions/sub-routines that were causing me problems.  That way I could have nVision run in the background but still provide messages about what state the code was in during particular points in the program run.

%d bloggers like this: