Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 318
  • Last Modified:

How to exit the calling procedure when the user cancels a sub-procedure

I am trying to find a way to exit the calling procedure when the user cancels a sub-procedure (a procedure called from within another procedure);
MyTestSub()

Dim Vars ' declare variables
     
On Error GoTo MyErrorHandler

Call MyFirstSub
     ' In this sub I prompt the user to cancel if a certain condition is true
     ' Answer = MsgBox("Do you want to continue ?", vbOKCancel, "Multiple Currency Types Selected")
     ' If I cancel here it goes on to the next sub - MySecondSub
     ' I want to have it exit MyTestSub
 

Call MySecondSub

Call OtherSubs

 
 MsgBox "Processing Complete for Business Report"

Exit Sub

MyErrorHandler:
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
   
End Sub
0
Ed_CLP
Asked:
Ed_CLP
  • 4
  • 3
1 Solution
 
andrewssd3Commented:
There are various approaches to this issue, including raising custom errors and handling them, but I prefer simply to make MySecondSub a Function returning a Boolean value - True if it succeeds, and false if the user cancelled.

Then you can use code like

     If Not MySecondSub() Then Exit Sub

Open in new window

0
 
NorieData ProcessorCommented:
You can end all code execution with End.
0
 
dlmilleCommented:
not for points...

I follow @andrewssd3 style.    It would be:

if not myFirstSub() then exit sub

Dave
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
andrewssd3Commented:
Yes - just saying End is a bit brutal - you would usually need to do some tidying up, destroy objects, etc.
0
 
NorieData ProcessorCommented:
You could say turning a sub into a function is a bit much.

I suppose there's also the option of a public variable.

I'm sure there's other methods too.:)
0
 
andrewssd3Commented:
Agreed - It's really just a matter of preference.  I've got in the habit of making all called procedures Functions because it does generally make life easier, and you almost always need to know whether a called subroutine has run successfully.  I know people who like to raise custom errors for everything and have elaborate error handling.
0
 
NorieData ProcessorCommented:
Can't say I've not done that but not very often.

Error handling  in VBA...mmmm.:)
0
 
andrewssd3Commented:
inmorie - my feelings exactly - best avoided!
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now