Understanding what response codes come back from MsgBox

前端 未结 8 1731
春和景丽
春和景丽 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:30

    It's very poorly written code, "6" and "7" are the values of the constants "vbYes" and "vbNo" where are returned when the user clicks Yes or No on the dialog.

    Reference: http://www.techonthenet.com/access/constants/msgbox_ret.php

    The code should say

    If message = Constants.vbYes 
    

    instead of

    If message = 6
    

    So that it is clear what is happening.

    0 讨论(0)
  • 2021-02-19 09:36

    6 and 7 are the return codes from the MsgBox method. Basically, when MsgBox is called, it shows a message-box to the user, who clicks either "Yes", "No", or "Cancel". The user's selection is returned from the MsgBox method as a number, where 6 is Yes, and 7 is No.

    It is considered best-practice not to use these numbers in your code directly, but instead to use Microsoft supplied constants which represent them. Your code could be re-written as:

    Private Sub CommandButton1_Click()
        Dim message As Integer
        message = MsgBox("Click Yes to Proceed, No to stop", vbYesNoCancel, "Login")
        If message = vbYes Then
            Range("A1").Value = "You may proceed"
            ActiveWorkbook.Activate 
        ElseIf message = vbNo Then
            ActiveWorkbook.Close
        ElseIf message = vbCancel Then
            'Do nothing.
        End If
    End Sub
    
    0 讨论(0)
提交回复
热议问题