检查用户select的范围或取消

我有以下代码,提示用户select一个单元格范围。

我很难检查范围是否有效(即他们是否只是在input框中input一个数字?),或者他们是否按下取消。 我如何区分?

Do While (True) Dim mInput As Range mInput = Application.InputBox(Prompt:="Please select the cells.", Type:=8) If (mInput Is Nothing) Then Exit Sub End If If (mInputRange.Columns.Count <> 1) Then MsgBox "There must be only one column selected.", vbOKOnly Else End If Loop 

如果Excel无法将其转换为范围,Excel会在返回结果之前产生一个错误。 尝试自己做。

另外,我认为你已经在做这个,但你需要使用

 set mInput = Application.InputBox(Prompt:="Please select the cells.", Type:=8) 

代替

 mInput = Application.InputBox(Prompt:="Please select the cells.", Type:=8) 

如果按下取消,也会引发错误,这意味着您需要使用某种错误检查例程:

 Sub test() On Error GoTo handler Dim rng As Range Set rng = Application.InputBox("a", Type:=8) Debug.Print rng.Address Exit Sub handler: Select Case Err.Number Case 424 MsgBox "Cancelled.", vbOKOnly + vbInformation, "Cancellation dialog" Case Else Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext End Select End Sub 

虽然mkingston的代码工作(我upvoted),我认为最好是testingNothing然后恢复到error handling程序。 代码然后可以stream动到一个动作,或采取另一个path,而不是需要恢复发布error handling(我保留的问题是无法预料的)

 Sub test() Dim rng As Range On Error Resume Next Set rng = Application.InputBox("Please select the cells", Type:=8) On Error GoTo 0 If Not rng Is Nothing Then If rng.Columns.Count <> 1 Then MsgBox "There must be only one column selected.", vbOKOnly Else 'do stuff End If Else MsgBox "User either cancelled range selected or selected an invalid range", vbCritical End If End Sub