Handle cancellation of InputBox to select range

后端 未结 6 1871
小蘑菇
小蘑菇 2020-12-10 06:20

I have the following piece of code:

dim selectRange as Range
Set selectRange = Application.InputBox(\"Select your range\", \"Hello\", , , , , , 8)

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 06:41

    I went with a cleaner solution:

    Dim InputValue As Range
    On Error Resume Next
    Set InputValue = Application.InputBox("Select Range","Obtain Range", Type:=8)
    Err.Clear
    If InputValue Is Nothing Then
        GoTo ExitApp:
    End If
    

    This will clear the error message and catch the "nothing" value returned to InputValue. Usefully, this doesn't interrupt a submission of no information, which Excel just loops back to requesting input automatically, but the user may need to add additional error handling for bad data entry.

    Down code, add:

    ExitApp:
        Exit Sub
    

    For exiting, which can be usefully shared between multiple input cancel handlers.

提交回复
热议问题