PDA

View Full Version : [SOLVED] MSGBOX VBOKONY, Cancel exits sub.



V.B.A.02
07-22-2017, 10:31 PM
Hello Everyone,

I am trying to do something like, macro to stop going further, if close button (X button, top right) or ESC button is used while a msgbox (VBOK OKnly) is appearing, Please see below code and suggest..


If MsgBox("Test, if it exits sub?", vbOKOnly, "Test") <> vbOK Then Exit Sub

When I run this, I get msgbox response = 1 in every case.

Regards,

YasserKhalil
07-22-2017, 10:48 PM
Hello
I think you would use "vbYesNo" as "vbOKOnly" has one default response which is OK .. so if you need flexibility you would use "Yes" / "No" to decide what after ..
Try this



Sub Test()
Dim answer
answer = MsgBox("Test, If It Exits Sub?", vbOKCancel, "Test")

If answer = vbOK Then
MsgBox "OK Is Pressed": Exit Sub
ElseIf answer = vbCancel Then
MsgBox "Cancelled"
End If
End Sub

V.B.A.02
07-22-2017, 11:43 PM
Yup, I was thinking to do it with VBOKONLY.

thanks

YasserKhalil
07-23-2017, 01:39 AM
You're welcome. Hope I can offer some useful help for you

mdmackillop
07-23-2017, 03:41 AM
You could use a simple userform made to resemble a message box
Module 1 code


Public Chk As Boolean
Sub Test()
Do
x = x + 1
If x = 5 Then
Chk = False
UserForm1.Show
If Not Chk Then Exit Do
End If
Loop Until x = 10
MsgBox x
End Sub

Userform button code

Private Sub CommandButton1_Click()
Module1.Chk = True
Unload UserForm1
End Sub

p45cal
07-23-2017, 04:14 AM
(looks like mdmackillop beat me to it!)

Yup, I was thinking to do it with VBOKONLY.
You're out of luck with a MsgBox on that one, but if you must have that behaviour then a userform. See attached.
The code is quite verbose so that you can see the whys and wherefores.
It responds to the Esc key too.

mdmackillop
07-23-2017, 04:41 AM
Personally I would use VBOkCancel (or VBYesNo) with Default Button value as appropriate. Why confuse things?

V.B.A.02
07-25-2017, 04:24 AM
Thanks for help.. it worked great. now I have more than one options. Thanks