处理InputBox的取消select范围

我有以下一段代码:

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

当用户select取消input框提示时,它将返回error of Object not set

我试图使用Variantvariablestypes,但我无法处理它。 如果取消,则返回False ,同时在select范围的情况下返回InputBox的Range。

我怎样才能避免这个错误?

使用input框select范围时,这是一个问题。 在返回范围之前,Excel会返回一个错误,并且当您按下取消时会出现此错误。

因此,你应该积极处理这个错误。 如果您不想在按下取消button时发生任何事情,则可以使用如下所示的代码:

 Sub SetRange() Dim selectRange As Range On Error Resume Next Set selectRange = Application.InputBox("Select your range", "Hello", , , , , , 8) Err.Clear On Error GoTo 0 End Sub 

我迟到了这里的聚会,但是这是我能find的唯一的地方,解释了为什么我只是无所事事地检查我的variables。 正如接受的答案中所解释的,范围对象上的vbCancel与string对象的处理方式不同。 错误必须被error handling程序捕获。

讨厌error handling程序。 所以我把它隔离到自己的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 

现在在我的主要分我可以

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

无论如何,这与接受的答案不同,因为它允许用户只用特定的error handling程序来处理这个错误,而不需要resume next或者让程序的其余部分以相同的方式处理。 如果有人像我一样在这里结束了。

虽然这个问题有点老,我仍然想要显示正确的方法来做到没有错误。 你可以通过函数或子类来完成。

你的主要过程是这样的:

 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 

Subway(有趣的)是:

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

这个函数看起来像这样:

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

现在只需使用你喜欢的方式,并删除未使用的行。

如果调用子函数或函数,则不需要Set参数。 也就是说, InputBox返回对象并不重要。 所有你需要做的,就是检查参数是否是你想要的对象,然后相应地处理它。

编辑

另一个聪明的方法是使用像这样的集合相同的行为:

 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 

如果您还有任何问题,请询问;)

我发现检查你提到的“Object required”错误是处理取消的一种方法。

 On Error Resume Next dim selectRange as Range ' InputBox will prevent invalid ranges from being submitted when set to Type:=8. Set selectRange = Application.InputBox("Select your range", "Hello", , , , , , 8) ' Check for cancel: "Object required". If Err.Number = 424 Then ' Cancel. Exit Sub End If On Error GoTo 0