Message Boxes

Visual Basic for Applications · Wikibooks

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From Wikibooks, under CC BY-SA 4.0, as the source states it. This page at Wikibooks.

    Message Boxes

    Summary

    This code block contains a message box function for YES, NO or CANCEL.

    VBA Code

    Option Explicit
    Sub TestYesNoCancel()
        'run to test message box
        
        Dim bDefault As Boolean
        
        If YesNoCancel(bDefault) = True Then
            If bDefault Then
                'do default stuff
                MsgBox "Using default"
            Else
                'do other stuff
                MsgBox "Using other"
            End If
        Else
               'do cancelled stuff
            MsgBox "User cancelled"
            Exit Sub
        End If
    End Sub
    
    Function YesNoCancel(bDefault As Boolean) As Boolean
        'Message box for yes, no, or cancel
    
        Dim Msg As String, Style As Long, Title As String
        Dim Reply As Integer
    
        'assignments
        Msg = "Do you want the default ?" & vbNewLine & vbNewLine & _
              "Select :" & vbNewLine & _
              "YES ;  for the default," & vbNewLine & _
              "NO ;   for some other," & vbNewLine & _
              "CANCEL ;  to quit."                              'message
        Style = vbYesNoCancel + vbQuestion + vbDefaultButton1   'buttons.
        Title = "Yes, No, Cancel layout..."                     'title.
    
        'show message box
        Reply = MsgBox(Msg, Style, Title)
    
        'resolve choice
        Select Case Reply
        Case vbYes
            bDefault = True
            YesNoCancel = True
        Case vbNo
            YesNoCancel = True
            Exit Function
        Case vbCancel
            Exit Function
        End Select
    
    End Function
    

    See Also