输入框错误处理

时间:2013-05-01 10:51:13

标签: excel excel-vba vba

我在处理与输入框相关的错误时遇到问题"取消"单击。或者换句话说,如果输入的值为null,则它在sub中返回错误。我试过环顾四周,似乎仍然无法做到这一点。这是我的尝试:

Private Sub bttnSavingsExpected_Click()
Dim expected() As String
Dim nPeriods As Integer
Dim counter As Integer
Dim savings As Single

With ActiveSheet.Range("A13")
    nPeriods = Range(.Offset(1, 0), .End(xlDown)).Rows.Count
End With

ReDim expected(1 To nPeriods)

counter = 1

For counter = 1 To nPeriods
    expected(counter) = Range("A13").Offset(counter, 0).Value
Next

TryAgain:
On Error GoTo ErrH
counter = 1
For counter = 1 To nPeriods
    savings = InputBox("How much savings do you expect from " & expected(counter) & "?", "Savings?", Range("A13").Offset(counter, 1).Value)
    If savings = "" Then
        Exit Sub
    Else
    Range("A13").Offset(counter, 1).Value = savings
    End If
Next

Exit Sub
ErrH:
MsgBox "Please enter value. If the default value is desired then please click 'OK'.", vbOKOnly, "Do Not Click Cancel"
GoTo TryAgain

End Sub

通过这种尝试,即使我点击了" Ok",也会在第一次点击时显示MsgBox是否有输入。第二次尝试点击" OK"或"取消"导致被踢回编辑。

2 个答案:

答案 0 :(得分:3)

您有Dim savings As SingleIf savings = "" Then。多数民众赞成总是出错

尝试使用Dim savings As Variant

答案 1 :(得分:0)

确保将“收件箱”的变量设置为“”,然后测试False的值。比我见过的其他任何事情都要容易得多:

Sub WolfPackURL_input()
Dim TheURL As String
Dim SaveURL As Hyperlink
Set savedURL = Sheets("Data").Range("I1")

TheURL = ""
TheURL = Application.InputBox("Input the Sign-Up URL", "Wolfpack Weekly Players URL", "http://something", 1)

If TheURL = "False" Then
    Exit Sub
End If

ThisWorkbook.Worksheets("Data").Activate
Sheets("Data").Range("I1").Hyperlinks.Delete
Sheets("Data").Range("I1").ClearContents
Sheets("Data").Range("I1").Clear

ActiveSheet.Hyperlinks.Add anchor:=Sheets("Data").Range("I1"), Address:=TheURL, ScreenTip:="Open file", TextToDisplay:=TheURL

End Sub