处理由于Inputbox
按钮未按任何内容或按OK
按钮或任何内容而导致的任何错误时,处理Cancel
的最明智的方法是什么?除了我的脚本中给出的条件之外的错误数据输入。
Sub Inputbox_Clarity()
Dim feeding As String
feeding = InputBox("Enter something you wish or do whatever")
If feeding < 1000 Or feeding > 3000 Then Exit Sub
ActiveSheet.Range("A1") = feeding
End Sub
答案 0 :(得分:1)
这是一个小样本:
Sub Inputbox_Clarity()
Dim feeding As Variant
feeding = InputBox("Enter something you wish or do whatever")
If feeding = "" Then
MsgBox "you entered nothing or touched cancel or clicked the red x"
Exit Sub
End If
If Not IsNumeric(feeding) Then
MsgBox "you gave me a non-numeric"
Exit Sub
End If
If feeding < 1000 Or feeding > 3000 Then
MsgBox "you gave me out-of range"
Exit Sub
End If
ActiveSheet.Range("A1") = feeding
End Sub
答案 1 :(得分:1)
如果我将变量feeding
从String
更改为Variant
,那么它可以处理任何错误,无论其类型如何。在这里。
Sub Inputbox_Clarity()
Dim feeding As Variant
feeding = InputBox("Execution won't take place until the input is between 1000 to 3000")
If feeding < 1000 Or feeding > 3000 Then Exit Sub
ActiveSheet.Range("A1") = feeding
End Sub
答案 2 :(得分:1)
不使用InputBox函数,另一种方法是使用Application对象的InputBox方法,该方法包含内置错误处理。
Sub Inputbox_Clarity()
Dim feeding As Variant
feeding = Application.InputBox("Enter a number >= 1000 and <= 3000", "Number", Type:=1)
If feeding = False Then Exit Sub
If feeding < 1000 Or feeding > 3000 Then Exit Sub
ActiveSheet.Range("A100") = feeding
End Sub
或者,您可以使用Do / Loop继续提示输入有效数字,或者直到按下“取消”按钮。
Sub Inputbox_Clarity()
Dim feeding As Variant
Do
feeding = Application.InputBox("Enter a number >= 1000 and <= 3000", "Number", Type:=1)
If feeding = False Then Exit Sub
Loop While feeding < 1000 Or feeding > 3000
ActiveSheet.Range("A100") = feeding
End Sub
希望这有帮助!