Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel: Break on Error doesn't work in user-defined function

It seems that when VBA code is called from a cell formula (ie. a "User Defined Function" or UDF), the usual VBA Break On Error doesn't work.

The only place I can find this behavior documented is a couple of lines in an article called "Developing User-Defined Functions for Excel 2007 and Excel Services":

Error handling returns #VALUE errors. All exceptions thrown by the UDF code are returned into the Excel worksheet as #VALUE errors.

Even if you set Error Trapping to "Break on All Errors" and single-step your code**, you will never see the VBA Run-time Error dialog - Excel just quietly abandons execution without telling you what went wrong. Of course this makes debugging more difficult than it needs to be.

There are some potential workarounds involving On Error but I'd rather not clutter up my code just to find out where an error was raised.

Is there some Excel / VBA option I've overlooked which will make Break On Error work normally? I'm using Excel 2003.

** The only way to get into the debugger when called from a cell is to set a breakpoint or use a Stop statement

like image 753
Hugh Allen Avatar asked Jul 08 '11 04:07

Hugh Allen


People also ask

Why a custom function is not working in Excel?

As for the custom ones, Excel cannot validate the VBA code and identify other cells that could also affect the result of the custom function. Therefore, your custom formula may not change when you make changes to the workbook. To fix the issue, you'll just need to use the Application. Volatile statement.

How do I enable user defined function in Excel?

To enable UDFsUnder Excel Services Settings, click User-defined functions. On the Excel Services User-Defined Functions page, click Add User-Defined Function to open the Excel Services Add User-Defined Function Assembly page.


1 Answers

Best method would be to use the On Error GoTo ErrorHandler with a Stop reference followed by Resume.

Need to be careful not to get into an infinite loop with resume as UDFs run almost continually (if this happens hit Esc repeatedly)

So in your code add: On Error GoTo ErrorHandler near the start of your function and then right at the end before End Function:

Exit Function
ErrorHandler:
MsgBox Err.Number & vbCrLf & Err.Source & vbCrLf & Err.Description
Stop
Resume

The Exit Function stops this code running in normal operation. If an error is encountered a messagebox with the details will pop up, the code will break (due to Stop) and you can step through back into your code (hopping back via the resume statement) using the next line command on the debug toolbar.

Of course don't forget to comment out the On Error GoTo ErrorHandler line when you're happy with your UDF.

like image 196
Zaberi Avatar answered Oct 01 '22 07:10

Zaberi