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)
我不喜欢错误处理,因为它将涵盖其他问题:
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)