使用VBA输入盒进行错误处理的奇怪流程?

Mat*_*ful 0 vb6 excel vba excel-vba

我试图理解为什么下面的代码没有给我预期的行为.

我想问用户一个十进制数(双).我有一个错误处理程序,但这个程序的行为方式,当我输入一个单词或数字时,它仍然会抛出错误.当我没有放任何东西(空输入)时它会捕获错误.

当我删除if条件时,它将按预期工作,但我不知道如何捕获空用户输入.

任何想法将不胜感激!

Sub MainTask()

Dim userInput As Double

TryAgain:
    On Error GoTo ErrorHandler
    userInput = InputBox("What is the amount purchased you would like to search for? ($)")
    If Len(userInput) = 0 Then
        Exit Sub
    End If
    MsgBox "You have entered a valid value!"
Exit Sub

ErrorHandler:
MsgBox "Please enter a valid value."
GoTo TryAgain

End Sub
Run Code Online (Sandbox Code Playgroud)

Sco*_*ner 6

我不喜欢错误处理,因为它将涵盖其他问题:

Sub MainTask()

Dim userInput As Variant
Dim output As Double

Do
    userInput = InputBox("What is the amount purchased you would like to search for? ($)")
    If Len(userInput) = 0 Then Exit Sub
    If Not IsNumeric(userInput) Then MsgBox "Please enter a valid value."        
Loop Until IsNumeric(userInput)

output = userInput
MsgBox "You have entered a valid value! " & output   

End Sub
Run Code Online (Sandbox Code Playgroud)

  • 的确,确实!后期处罚不能被夸大 - 特别是在循环中.我想,就像许多事情一样,#ItDepends =) (2认同)
  • @Rory FWIW - `Application.FunctionName`方法是后期绑定并且是Excel 95的抛出.主要区别在于:后期绑定性能,无Intellisense和无提示错误.虽然`Application.WorksheetFunction`似乎是可扩展的,但它确实具有对工作表函数的早期绑定引用,因此您获得早期绑定的性能,您获得Intellisense,并且您可以编译任何被滥用的早期绑定成员或缺少参数.例如,您不能使用`x = Application.WorksheetFunction.Sum`而不会得到*编译错误 - 参数不是可选的*. (2认同)