I have the following piece of code:
dim selectRange as Range
Set selectRange = Application.InputBox("Select your range", "Hello", , , , , , 8)
When a user chooses Cancel the InputBox prompt, it returns error of Object not set
.
I have tried to use a Variant variable type but I can't handle it. In case of cancelling, it returns False
, meanwhile in case of selecting a range, it returns Range of InputBox.
How can I avoid this error?
While this question is a bit older I still want to show the proper way to do it without errors. You can do it either to it via function or with a sub.
Your main procedure is something like this:
the Sub-way (funny) would be:
And the function would look like:
Now simply use the way you like and delete the unused line.
If calling a sub or a function you do not need to
Set
the parameter. That said, it doesn't matter if theInputBox
returns an object or not. All you need to do, is to check if the parameter is the object you want or not and then act accordingly to it.EDIT
Another smart way is using the same behavior with a collection like this:
If you still have any questions, just ask ;)
If I use Dirks second answer inside a for loop and I want to exit my sub, it is not enough to execute an Exit Sub inside his IF statement
I found that if I use Exit Sub standalone inside a for loop, I will not exit my sub in all cases, however, in most cases only exit the for loop.
Here you have Dirks code
Here is what I made to work as a example:
If you press cancel at anytime in the five runs, the Sub is shutdown with the above code and you will never see Program completed printed.
However if you remove boolExit from the above, the code after the For loop is still being run if you press cancel in any of the 1+ runs and you will see Program completed even when that is not true.
This is a problem when selection a range with an inputbox. Excel returns an error before the range is returned, and it carries this error on when you press cancel.
You should therefore actively handle this error. If you don't want anything to happen when you press cancel, you can just use the code like this:
I'm late to the party here but this was the only place I could find that explained why I was having trouble just checking my variable for nothing. As explained in the accepted answer, the
vbCancel
on a range object isn't handled the same way as a string object. The error must be caught with an error handler.I hate error handlers. So I segregated it to its own function
Now in my main sub I can
Anyhow this is not the same as the accepted answer because it allows the user to only handle this error with a specific error handler and not need to
resume next
or have the rest of the procedure handled the same way. In case anyone ends up here like I did.I have found that checking for the "Object required" error that you mentioned is one way of handling a cancel.