Reputation: 23
In the code below, I would like to have it so when the sub code()
is run, and the condition
is equal to false
, then it will end the sub test()
, not display the message "hello"
and stop all scripts. Could someone please tell me how to do so?
Private Sub test()
Call code
MsgBox ("Hello")
End Sub
Private Sub code()
If Condition = False Then
End If
MsgBox ("Hello World")
End Sub
Upvotes: 1
Views: 795
Reputation: 812
In my case, I had set On Error
Do nothing. So, it was an error and VBA compiler wasn't showing any error.
On Error GoTo errorRoutine
'Your Code Goes Here...
Exit Sub
errorRoutine:
I simply found the error and it starts working.
Upvotes: 0
Reputation: 57114
What you want to do is use Return
or Exit Sub
in the following way:
If condition = false Then
Call condition()
Return
End If
https://msdn.microsoft.com/en-us/library/dz1z94ha.aspx tells you
When a Sub procedure returns to the calling code, execution continues with the statement after the statement that called it. The following example shows a return from a Sub procedure.
Sub mySub(ByVal q As String) Return End Sub
The
Exit Sub
andReturn
statements cause an immediate exit from a Sub procedure. Any number of Exit Sub and Return statements can appear anywhere in the procedure, and you can mix Exit Sub and Return statements.
To break out of the calling sub as well, the inner sub has to return a value indicating to the calling sub that it should not print, there is no built-in way.
Upvotes: 2
Reputation: 12602
Use End
keyword:
Const Condition = False
Private Sub test()
Call code
MsgBox ("Hello")
End Sub
Private Sub code()
If Condition = False Then
End
End If
MsgBox ("Hello World")
End Sub
Upvotes: 0
Reputation: 363
You need to use if then else
Private Sub code()
If condition = false Then
Call condition()
else
MsgBox("Hello World")
End If
End Sub
Private Sub condition()
MsgBox("Failure")
End Sub
Upvotes: 0