Understanding what response codes come back from MsgBox

msgbox, vba

Solution

`MsgBox` does return an `Enum(eration)` called `MsgBoxResult`, which is basically nothing else then numeric values with a 'label'. 6 and 7 in this case are members of this enum, which are mapped to the answers `Yes` and `No`.

Using so called 'magic numbers' instead of Constants or Enums should avoided whenever possible.

Basically, you could rewrite the code to this:

Dim message As Integer
message = MsgBox("Click Yes to Proceed, No to stop", vbYesNoCancel, "Login")
If message = MsgBoxResult.Yes Then
    Range("A1").Value = "You may proceed"
    ActiveWorkbook.Activate
ElseIf message = MsgBoxResult.No Then
    ActiveWorkbook.Close
End If

Might be that the Enum is called vbMsgBoxResult or something... I don't have an Office to verify this, just Visual Studio.

While we are on it... this might be easier to understand:

Select Case MsgBox("Click Yes to Proceed, No to stop", vbYesNoCancel, "Login")
    Case MsgBoxResult.Yes
        Range("A1").Value = "You may proceed"
        ActiveWorkbook.Activate

    Case MsgBoxResult.No
        ActiveWorkbook.Close

    Case MsgBoxResult.Cancel
        ' he clicked cancel '

End Select

Problem

I'm very new to programming and I'm just starting to learn VBA with excel. I came across on this website and did the examples here but I have question about this code: I know the variables are declared using "Dim" statement "Message" here is the variable with a data type of integer. What I don't clearly understand is; what is the meaning of "6" here and "7". I believe they come from somewhere. But as I just started learning this program, I don't have any idea. Could you please tell me how it end up to "6" and "7". I believe there is some basis here ``` Private Sub CommandButton1_Click() Dim message As Integer message = MsgBox("Click Yes to Proceed, No to stop", vbYesNoCancel, "Login") If message = 6 Then Range("A1").Value = "You may proceed" ActiveWorkbook.Activate ElseIf message = 7 Then ActiveWorkbook.Close End If End Sub ``` Thank you for your help:-) ======= Thanks guys for the answers, they're very helpful. Yes this thread has been already posted in superuser site. I was informed that this question should belong here so I posted it here after reading that they will do it automatically from superuser to stackoverflow. thanks once again

Original source