How do you use exception handling in visual basic? - excel

How do you handle exceptions in visual basic?

VBA doesn't call it exception handling, rather it calls it error handling and it has a different syntax than what can be found in VB.Net or Java etc.
You need to research the On Error statement, specifically the On Error Goto <LABEL> where you can say that if any error occurs, then go to the specified label where you put your error handling code.
You can also tell the code to ignore errors by doing On Error Resume Next, but this should normally only be used very sparingly for as few lines as possible and then needs to be followed by On Error Goto 0 to reset the error handling.
See these articles for more information:
Error Trapping with Visual Basic for Applications
Error Handling In VBA

Related

How do I find host specific 1004 Descriptions

I am working on a language- (English, German, French, ...) and host (Excel, Word, PP, Access, ...) agnostic VBA-Error handling, and reporting system (using Excel as my VBA development platform).
Lately, I was trapping a VBA 1004 error coming up with an Err.Description I never "saw" until that date. Until now, I spent some hours, hopefully not waisted, to explore what's behind that "magic" 1004 error number.
The best general explanation I found so far (including Microsoft's domains) was:
Quote>>> Error 1004: Application-defined or object-defined error. This is a very common catch-all error message. This error occurs when an error doesn’t correspond to an error defined by VBA. In other words, the error is defined by Excel (or some other object) and is propagated back to VBA. << VBA Error Codes
So, my question is:
Is there a native VBA way to get this host-specific
(Excel/Word/PP/...) 1004 error messages? (I am pretty sure, there
isn't)
Or, is there a place on the internet that list them all, these host-specific Descriptions (and I was only to drunk to google it ;-)
Or, do you know any Office resource file(s) (DLL/EXE/whatever format) that I might look inside to find the Err.Descriptions strings I'm looking for?
BTW, I'm an experienced developer - you do not have to explain anything to me, but just tell me, if you know ;-)
These are my findings, so far:
The VBA's error# 1004 is a dummy/placeholder error assigned a generic, internationalized(!) descriptional text depending on the ERROR_CONTEXT.
A real ERROR_CONTEXT related error only exists at RUNTIME and it must deal with a real specific error. That is, we CANNOT create a specific #1004 Err.Description from within our immediate window typing something like so: Error 1004 {enter}
This only echoes the default err.description.
The ERROR_CONTEXT always depends on the VBA host we are in while executing our code. Thus, the textual Err.Description never clashes between different hosts. BUT, the Err.Number does as it always is 1004.

How to suppress excel compiler error from VB6

I am executing the Excel 'Debug -> Compile VBAProject' from a VBA project like below,
Public Function CheckForCompilerErrors()
On Error GoTo compileerr
ExcelObject.ActiveWorkbook.VBProject.VBE.CommandBars.findcontrol(ID:=578).Execute
Exit Function
compilerErr:
MsgBox "Compilation failed. Give Debug->Compile VBAProject and fix the compilation errors."
End Function
Here after running the .Execute, Excel VBA is throwing the error "Compiler Error: User-defined type not defined.".
But actually I want to suppress this Excel VBA error. That's the reason why I added error handler. But in the above case, it is not going to error handler.
Maybe what I am suspecting is, since the .Execute got successfully called (which invokes Debug->Compile VBAProject) whether there is any error or not, it returns success and not going to error handler.
Is there anyway, I can suppress the Excel VBA compiler error.
When you are sending the click to the Compile button, there will be an error if the button is unavailable, which it is if you just compiled something. That error you can catch and suppress.
If there is a compilation error, you won't be able to catch it this way.

Runtime Error with Workbook Auto Open + MsgBox as response for an user

I was trying to put MsgBox into my code. It should be shown only if call Table.auto_open doesn't work.
In my final document are few of those Call statements and i would like to get only that msgbox, if one or few of Call statements doesn't work.
For Example "Auto_open" will be changed to "auto_op" what naturally won't be possible, because in real sheet it is "Auto_open".
Or in another example that code from "Auto_open" is broken.
I need some help with that. It's seems to be simple, but I think it's not possible to put that "On Error GoTo" code in that place just like that, because Call doesn't give me a real error?
Can someone say me what I'm doing wrong? I tried already all combinations of that Error handling, nothing works.
Private Sub Workbook_Open()
On Error GoTo Error
Call Tabelle1.auto_open
Exit Sub
Error:
MsgBox "Failure"
Resume Next
End Sub
If you are calling a sub that does not exist you will get a Compile Error.
You can check for these errors by going to VBE>Debug>Compile VBAProject (or just try to run the macro)
Compile Errors, much like Syntax Errors, have to be handled before you can run a sub. Thus, these errors cannot be handled with code such as On Error GoTo EH or On Error Resume Next as these are only activated once the sub is actually running.
You can convince yourself of this by producing a common Compile error, or Syntax error, and trying to step through the code (F8). You will notice that the error occurs on your Sub [Name] () line, which indicates that you never actually entered your sub before the error occurred. Thus, you can intuitively see that your error handler will never actually be activated, resulting in an error message being displayed.
Once you have accounted for all Compile/Sytax Errors, you can check out this link, which will explain how you can handle Run Time Errors when you are calling other sub procedures from a sub.

Err.Number not populating for 'Excel Ran Out of Resources' error

I've developed a program using Excel VBA which occasionally causes an 'Excel Ran Out of Resources' error.
Closing the file, reopening, and rerunning the macro always fixes whatever issue created the error. I know that preventing the error in the first place is best practice, but am resigned to believe that it's unavoidable.
So, I would like to alert the user of the error, instead of Excel doing it, and perform some actions once the error has been detected. The problem is that I can't get VBA to recognize the error using the On Error GoTo ErrorHandler routine or the Err.Number property. I never get to the msgbox below:
My code is as follows:
Sub test()
On Error GoTo ErrorHandler
Calculate
ProcedureDone:
Exit Sub
ErrorHandler:
MsgBox "Error", vbOKOnly, "Oops"
Resume ProcedureDone
End Sub
Any insight would be fantastic since I've been searching for several days and haven't been able to find a work around.
I just happened to run across another issue that sounds like yours.
The point from the other thread is that Excel does not treat these application method results as VBA errors. Rather, they are Excel alerts, and they can be suppressed but not trapped in VBA as errors.
The way I interpret this is that when you execute certain application methods from VBA, it does not raise errors that VBA can trap. Rather, Excel interacts with the user as if the user had issued a GUI command. On the other hand, if an application method is designed to interact with VBA (e.g., if it returns a value), then VBA might be able to handle its errors.
This is distinct from the way VBA handles worksheet functions rather than application methods. VBA can intercept errors raised by worksheet functions, as noted in "Error Handling With Worksheet Functions" here.
I realize this does not solve your problem, but it gives you an idea of why.

Errors Raised within Class Debug As If Raised at Property Call

I am (unfortunately) developing an application in Excel 2000 VBA. I believe I have discovered that any error raised within a Custom Class property, function, or sub debugs as if the error were raised at the point in the VBA code where the property is called. That is, the VBE debugger does not take me to the point in the Class property where the error occurred, but instead where the property was first entered (from a Module Sub or Function, e.g.) This makes it frustrating to develop anything more than the most shallow OO Excel 2000 VBA code since I have to step line-by-line through every Class method to discover the instructions causing an error.
Am I missing something or is this a known bug I have to deal with in Excel 2000? Has this been fixed in 2003 or 2007?
Example code:
'''''''''''''''
'In Module1:
Public Sub TestSub1()
Dim testClass As Class1
Dim testVariant As Variant
Set testClass = New Class1
testVariant = testClass.Property1 'Debugger takes me here...
End Sub
''''''''''''''
' In Class1
Property Get Property1() As Variant
Err.Raise 666, , "Excel 2000 VBA Sux!" 'But error is actually thrown here.
End Property
For Office 2003 you will get this behaviour when the debugger is configured to break on unhandled errors (the default configuration).
If you want it to break on the Err.Raise line, you need to configure it to break on all errors (Tools/Options/General/Error Trapping/Break on All Errors).
I believe it's the same for Office 2000 but don't have a copy to check.
This page is a very good resource on error handling in VBA:
Error Handling and Debugging Tips and Techniques for Microsoft Access, VBA, and Visual Basic 6
This "feature" is the same in Excel 2003 and I'd be surprised if it's different in 2007.
The same still holds true in Excel 2010 - that's where I met this behaviour.
To quote Chip Pearson's site:
There is absolutely no reason to use an error trapping setting other than Break In Class Module.
His description of the difference between the error modes:
When you are testing and running your code, you have three error trapping modes. The first is Break On All Errors. This will cause the debugger to open if any error occurs, regardless of any On Error handling you might have in the code. The second option is Break On Unhandled Errors. This will cause the debugger to open if the error is not handled by an existing On Error directive. This is the most often used option and is the default setting. The third option, Break In Class Module is the most important and least used. It is not the default error trapping mode, so you have to set it manually.
The Break In Class Module is the most important because it will cause the debugger to break on the line of code within an object module that is actually causing the problem. The Break In Class Module setting is in the Options dialog accessible on the Tools menu. It is on the General tab of the Options dialog, as shown below.

Resources