Link to home
Start Free TrialLog in
Avatar of naqayya
naqayya

asked on

Stop code running totally in called sub

I have a sub that calls another sub.

When an error occurs in the called sub (2nd sub) how can I make the code stop running totally and not go back to the 1st sub.

(My 2nd sub could be in the same module or in another module.)

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of deighton
deighton
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of selim007
selim007

deighton  will work fine.
you can also create a public variable for example Sub2Err as long.
- then if an error occures in the second sub you'll simply put the error number in the variable:
Sub2Err=err.number
- now the program counter should return to sub1.
here you'll test if the public variable Sub2Err contains an error number, if so u'll stop processing otherwise u continue executing the code:
if Sub2Err <> 0 then  'some error occured
exit sub
end if
'continue executing sub1 code

you can use this method if you don't want your function to return any code or if your function is already  returning something and you don't wanna pass variable by reference or let the function resturns a structure.
i recommend deighton method which is simple
private function sub2()
On error goto Err_Handler
...
exit sub

Err_Handler:
  if err.number = ### then
    end
  endif
end function

--
Note that the above will intercept an error and if a specified error occurs (replace ### with the desired error number) then the code will immediately stop, along with the application, and any open threads will remain open and you will lose resources...however, it will immediately stop the code as per your request!
you can try the below

Sub procedure1()
    call Procedure2
End sub

Sub Procedure2()
On error goto ErrHandler

'' Code in Procedure2

Exit sub
ErrHandler
     end
End sub

In case you want to do for some specific errors which occur in the procedure2 then in the Error Handler code you can write as
If Err.Number = (Error number) then
    END
else
    MsgBox Err.descrription, vbcritical
end if

jayeshshah, please read the guidelines at the bottom of this page regarding proposed answers.  (Notice that you duplicated much of my comment.) Most experts will place all entries only as comments.
Avatar of naqayya

ASKER

see rspahitz's comment