Understanding what response codes come back from MsgBox

前端 未结 8 2142
春和景丽
春和景丽 2021-02-19 08:32

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:

<
8条回答
  •  轮回少年
    2021-02-19 09:15

    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
    

提交回复
热议问题