Handle cancellation of InputBox to select range

后端 未结 6 1869
小蘑菇
小蘑菇 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:29

    I'm late to the party here but this was the only place I could find that explained why I was having trouble just checking my variable for nothing. As explained in the accepted answer, the vbCancel on a range object isn't handled the same way as a string object. The error must be caught with an error handler.

    I hate error handlers. So I segregated it to its own function

    Private Function GetUserInputRange() As Range
        'This is segregated because of how excel handles cancelling a range input
        Dim userAnswer As Range
        On Error GoTo inputerror
        Set userAnswer = Application.InputBox("Please select a single column to parse", "Column Parser", Type:=8)
        Set GetUserInputRange = userAnswer
        Exit Function
    inputerror:
        Set GetUserInputRange = Nothing
    End Function
    

    Now in my main sub I can

    dim someRange as range
    set someRange = GetUserInputRange
    if someRange is Nothing Then Exit Sub
    

    Anyhow this is not the same as the accepted answer because it allows the user to only handle this error with a specific error handler and not need to resume next or have the rest of the procedure handled the same way. In case anyone ends up here like I did.

提交回复
热议问题