wwla
wwla

Reputation: 41

Command Button in msgbox vba possible?

si it possible to add a command button in the msgbox window in vba?

For example, i want to add a cancel button that stops the code rather than continuing it. I could create a new userform, but it would be nice if i save some space and use the msgbox that is already here.

Upvotes: 1

Views: 3554

Answers (2)

BobtimusPrime
BobtimusPrime

Reputation: 174

VBA has several different types of MessageBoxes with built in command buttons for this very purpose. The type of buttons included in the message box is declared as the second parameter - MsgBox(Prompt, Buttons as)

The types you are probably interested in are:

  • vbYesNo
  • vbYesNoCancel
  • vbAbortRetryIgnore
  • vbOkCancel
  • vbRetryCancel

These Buttons return integer values that need to either be stored or used for comparison.

VBA has these integer answers stored as constants (e.g. vbOK = 1, VbCancel = 2, etc.) See Microsoft Developer Network MsgBox Function for more details on that.

Sub mySub()

Dim answer as Integer

answer = MsgBox("Would you like to choose yes?", vbYesNoCancel)

If answer = vbYes Then
   'Do whatever you want
ElseIf answer = vbNo Then
   'Do whatever
Else
   Exit Sub
End If

End Sub

Upvotes: 4

pokemon_Man
pokemon_Man

Reputation: 902

Try this:

If MsgBox("Cancel or Continue, are you sure?", vbOKCancel) = vbOK Then
     'continue whatever you want to do.
End if

Upvotes: 0

Related Questions