Handle cancellation of InputBox to select range

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

    While this question is a bit older I still want to show the proper way to do it without errors. You can do it either to it via function or with a sub.

    Your main procedure is something like this:

    Sub test()
      Dim MyRange As Range
    
      testSub Application.InputBox("dada", , , , , , , 8), MyRange 'doing via Sub
      Set MyRange = testFunc(Application.InputBox("dada", , , , , , , 8)) ' doing via function
    
      If MyRange Is Nothing Then
        Debug.Print "The InputBox has been canceled."
      Else
        Debug.Print "The range " & MyRange.Address & " was selected."
      End If
    End Sub
    

    the Sub-way (funny) would be:

    Sub testSub(ByVal a As Variant, ByRef b As Range)
      If TypeOf a Is Range Then Set b = a
    End Sub
    

    And the function would look like:

    Function testFunc(ByVal a As Variant) As Range
      If TypeOf a Is Range Then Set testFunc = a
    End Function
    

    Now simply use the way you like and delete the unused line.

    If calling a sub or a function you do not need to Set the parameter. That said, it doesn't matter if the InputBox returns an object or not. All you need to do, is to check if the parameter is the object you want or not and then act accordingly to it.

    EDIT

    Another smart way is using the same behavior with a collection like this:

    Sub test()
      Dim MyRange As Range
      Dim MyCol As New Collection
    
      MyCol.Add Application.InputBox("dada", , , , , , , 8)
      If TypeOf MyCol(1) Is Range Then Set MyRange = MyCol(1)
      Set MyCol = New Collection
    
      If MyRange Is Nothing Then
        Debug.Print "The inputbox has been canceled"
      Else
        Debug.Print "the range " & MyRange.Address & " was selected"
      End If
    End Sub
    

    If you still have any questions, just ask ;)

提交回复
热议问题