How to detect if user select cancel InputBox VBA Excel

后端 未结 3 975
我寻月下人不归
我寻月下人不归 2020-12-03 04:27

I have an input box asking user to enter a date. How do I let the program know to stop if the user click cancel or close the input dialog instead of press okay.

Some

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 05:23

    If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...

    EDIT to properly differentiate between empty string and cancel, according to this answer.

    Your example

    Private Sub test()
        Dim result As String
        result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
        If StrPtr(result) = 0 Then
            MsgBox ("User canceled!")
        ElseIf result = vbNullString Then
            MsgBox ("User didn't enter anything!")
        Else
            MsgBox ("User entered " & result)
        End If
    End Sub
    

    Would tell the user they canceled when they delete the default string, or they click cancel.

    See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx

提交回复
热议问题