Search code examples
vbabuttoncommandmessageboxmsgbox

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.


Solution

  • 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