MS Office Forum

Ask Question   UnAnswered
Home » Forum » MS Office       RSS Feeds

Exist Sub altogether

  Asked By: Lewis    Date: Feb 04    Category: MS Office    Views: 1438

Need help on the followings.

I want the "Exit For" in the Second Sub (called) to Exit the first
Sub (calling) as well.

In other words, at "Exit For", both Subs should stop.

Sub First()

For cnt = 1 To 5

k = k + 1

Call Second(k)

Debug.Print "k--" & k

Next cnt

End Sub


Sub Second(ByVal u As Single)

If u = 3 Then
Exit Sub 'Exit Second procedure
End If

Debug.Print "u--" & u

End Sub



5 Answers Found

Answer #1    Answered By: Maurice Hanson     Answered On: Feb 04

I assume you mean the exit  Sub, not "Exit For" ...

You can't do it with a single command. You'll need to write the exit code
in the caller yourself.

Answer #2    Answered By: Bellona Lopez     Answered On: Feb 04

Call Second(k)
a line such as:
If k = 3 Then Exit Sub
should do it.

But your example may be a bit more complicated, so another solution is
to set up a variable in the Declarations portion of the module (the
top) like:
Dim CarryOn As Boolean
then very early on in First() have the line:
CarryOn = True
and in Second() after
If u = 3 Then
CarryOn = False
in the If statement
and finally in First() after the line
Call Second(k)
If Not CarryOn Then Exit Sub

Answer #3    Answered By: Jonathan Harrison     Answered On: Feb 04

I would do something like this:

Sub First()

For cnt = 1 To 5

k = k + 1

If Second(k) Then

Exit Sub

End If

Debug.Print "k--" & k

Next cnt

End Sub

' Change this to a Function instead of Sub.

' Return True when we should exit  both functions.

Function Second(ByVal u As Single) as Boolean

If u = 3 Then

Second = True

Exit Function 'Exit Second procedure

End If

Debug.Print "u--" & u

Second = False ' This line is not necessary in VBA

' ...because False would be the default return value anyway.

' ...(This is not the case in future VB versions...)

End Function

Answer #4    Answered By: Gerald Cruz     Answered On: Feb 04

You can use End to terminate all macros.

Answer #5    Answered By: Zoar Mizrachi     Answered On: Feb 04

So Simply, yet So Beautiful. The ART of programming.

Didn't find what you were looking for? Find more on Exist Sub altogether Or get search suggestion and latest updates.