检查用户选择的范围或取消

时间:2012-03-20 23:42:36

标签: excel excel-vba vba

我有以下代码提示用户选择一系列单元格。

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

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

2 个答案:

答案 0 :(得分:5)

虽然mkingston的代码确实有效(并且我赞成),但我认为最好测试Nothing然后恢复为错误处理程序。然后代码可以转到某个操作,或者采取另一个路径,而不是需要恢复错误处理(我为无法预料的问题保留)

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

答案 1 :(得分:3)

如果无法将结果转换为范围,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