Object reference not set to an instance of an object

leonlai

Board Regular
Joined
Mar 22, 2019
Messages
77
Hi,

I use a Try-Catch block to catch errors in my code.
This is not strictly VBA code, but VB.NET code which is very similar.
I am not sure this is the appropriate forum.

I use a general exception to trap my error:

Code:
Try
Catch ex As Exception
End Try


When the error I have in mind happens, I always get this error message:
Object reference not set to an instance of an object

The error happens when a range is not selected when it is required to be selected.
Here is the code:

Code:
For Each CmtCell In SelectedRange
       If Not CmtCell.Comment Is Nothing Then CountCmts = CountCmts + 1
Next

I wish to use a more specific Exception to catch this type of error for 2 reasons:
(a) I can display a more specific and helpful message
(b) I can keep the general Exception to trap all other exceptions

Can anybody tell me which exception can be used?

I tried:

Code:
Catch ex As NullReferenceException     '// this works & gives the same message

Code:
Catch ex As ObjectDisposedException   '// this does not work

Thanks
Leon
 

Excel Facts

Last used cell?
Press Ctrl+End to move to what Excel thinks is the last used cell.
Can you show us the vba code you have ... Not the VB.net code .
 
Upvote 0
Hi, Jaafar

Thanks for your reply.

Unfortunately, there is no VBA code. Try-Catch applies only for VB.NET.
My question is more of a general type than a specific problem.

I used IntelliSense in Visual Studio to test all kinds of Exceptions, and it seems that only the NullReferenceException can replace the general Exception.

As I cannot ask my question more precisely, I prefer to close this thread which is too vague.

Best Regards,
Leon
 
Upvote 0

Forum statistics

Threads
1,214,834
Messages
6,121,874
Members
449,056
Latest member
ruhulaminappu

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top