2012-03-20 29 views
2

我有以下代碼,提示用戶選擇一個範圍的單元格。檢查用戶選擇的範圍或取消

我很難檢查範圍是否有效(即他們是否只是在輸入框中輸入數字?),或者他們是否按下取消。我如何區分?

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 
+1

僅供參考'做雖然(真)'與「Do While True」與「簡單」Do「相同,它更簡潔易讀。 – 2012-03-21 07:55:12

回答

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 
+0

非常感謝 - 作品一種享受。 :) – R4D4 2012-03-21 00:10:57

+0

很高興幫助:) – mkingston 2012-03-21 00:25:32

+0

+1爲一個良好的工作解決方案 – brettdj 2012-03-21 02:10:32

5

雖然mkingston的代碼確實有效(我upvoted),我認爲最好測試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 
+0

我完全同意。我的代碼更多的是爲了掌握這個概念。這個答案可能對不熟悉excel錯誤檢查的人有用(很可能是op :))。 – mkingston 2012-03-21 02:32:21

+0

像往常一樣好:) – 2012-03-21 08:55:23

+0

@ Jean-FrançoisCorbett公平點,雖然我會建議可能會在實施中變化。我同意,儘管如此,Brett的代碼就是一個更好的例子。 – mkingston 2012-03-22 23:02:52