Cancel BOTH Routines on Error

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a sub routine that works along and then calls a private sub to open a
file to import. When the 2nd sub errors out (or, more specifically, the user
cancels the selection of a file to import), I have the code go to an error
message and exit that 2nd sub. But then it continues on with the 1st sub from
whence it came and I want it to stop that one also. How do I make the 1st
routine also cancel when the 2nd routine has errored?
 
Change your 2nd sub to a boolean function that returns False if it errors
out. Then have your first sub exit if that value is returned to it.

HTH,
 
I probably didn't do it as efficiently as you did, but it worked.
I added the global name of MyError set as Boolean.
Then I added a statement after the first message that set MyError as True if
it got there. Then as it continued back to the first routine, I told it that
if it found that MyError was true upon return, to Exit the sub.

And how would you have done it?
 
I would change the 2nd Sub to a Function and then determine which values
you want to use to indicate that the Function completed normally or
failed (probably TRUE or FALSE). Then its a matter of detecting if the
user has selected a valid file, an invalid file or none at all
(canceled) probably using some sort of IF...THEN or SELECT CASE. To exit
out of the function add the code

myFunction = False 'Indicating that the function failed
Exit function

of course at the end of the function, you'll need
myFunction = True
End Function

In the calling SUB you would then use an IF...THEN to test the value
returned by the function as in

If myFunction() = False then
msgbox("Function crapped out")
exit sub
else
'whatever code you need
end if
 
That's a valid approach but be careful to think it through. As a global
variable it will retain its value until it is changed. Will you possibly be
calling the 2nd routine more than once? If so, does your 2nd routine set
MyError to False before it does anything else? If not you run the danger of
setting MyError to True on an error the 1st time you call it and it staying
that way forever, even though subsequent calls might be error free.

A global or even modular variable is overkill in this case (but no harm is
being done). Only 2 procedures reference it and you could just as easily
pass the value between them. It is not an uncommon requirement. If you find
the need for another boolean flag, and then another, etc. you could end up
with a lot of MyError2, MyError3 variables and run the danger of getting
them confused with each other within your code. I suspect that you will find
that simply getting the return value from a specific function is a lot less
troublesome in the long run.


HTH,
 
Back
Top