1

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.

wwla
  • 41
  • 1
  • 9

2 Answers2

4

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
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
BobtimusPrime
  • 174
  • 13
0

Try this:

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