虽然这个问题有点老了,但我仍然想展示正确的方法来做到这一点而不会出错。您可以通过函数或子函数对其进行处理。
你的主要程序是这样的:
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
子方式(有趣)是:
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
如果你还有任何问题,尽管问;)