Partilhar via


Error Handling and Macros: MacroError

I previously discussed the brand new OnError macro action that introduces some useful error-handling capabilities to macros. I ended up with the break-or-make question that I'm sure was on the heads of the error-handling-scarred people in the audience:

 

Can you have a global error handling macro like it is generally done in VBA?

 

Let me introduce you the MacroError object. It lives off of the Application object and it contains the last error that happened when running a macro. Actually, if you look at the object you will see a number of methods: ActionName, Arguments, Number and Description.  

 

All these methods contain information about the last failure, so ActionName will have the name of the action that failed; Arguments will have the argument values that the action that failed were called with and so forth. Number and Description has the error code and the description text of the failure. MacroName has the name of the macro that failed.

 

There's also a DoCmd.ClearMacroError (or ClearMacroError action) that will clear the last error.

 

Now, back to the original question. The way you can have a global error handling macro (or even VBA function as we'll see further) is by using an OnError with a macro name and in that name having a RunMacro that will call a separate macro. That macro, the global error handling macro, can make use of MacroError.ActionName, .MacroName and other information to do the error handling.

 

Here's a sample macro:

 

<Macro1 Macro>

 

          OnError (Macro Name, "Error")

  OpenForm (Form, "Form1", …)

Error: RunMacro ("ErrorHandler", …)

<ErrorHandler Macro>

 

          OnError (Fail, …)

  <do something>

 

If you'd rather hook all of this to your already existing VBA error handling function, you can use RunCode instead of RunMacro. And since we expose the MacroError in VBA you have the full range of capabilities you had in the macro world. 

 

Finally, you can use the TempVars that we previously talked about to pass data between your macro and the error handler code (in VBA or Macro).

Comments