我正在为一个课程项目开发预算计算器。基本上一切都很好,除了一点烦人的细微差别。
如果您未输入数字或输入负数,则会收到错误消息。但是,当你不小心输入一个字母时,得到错误,然后输入它刚刚退出的负数,我希望它显示该错误并循环回去,直到它们输入正数。
我在Visual Studio 2012中使用VBA,这是一个Windows窗体应用程序。
Dim strEntertainmentHeading As String = "Entertainment Expenses"
Dim strHeading As String = "Budget Alottment"
Dim strNonNumericError As String = "Error - Enter a number for the Expense"
Dim strNegativeError As String = "Error - Enter a positive number for the Expense"
Dim strEntertainmentInput As String = "Enter the amount for Entertainment Expenses"
Dim strEntertainment As String
Dim decEntertainment As Decimal
strEntertainment = InputBox(strEntertainmentInput, strEntertainmentHeading, " ")
Do
If strEntertainment = "" Then
Exit Sub
ElseIf IsNumeric(strEntertainment) Then
decEntertainment = Convert.ToDecimal(strEntertainment)
If decEntertainment >= 0 Then
lstBudget.Items.Add("Entertainment Expense: " & decEntertainment.ToString("C2"))
' Display error message if user entered a negative value
Else
strEntertainmentInput = strNegativeError
End If
Else
strEntertainmentInput = strNonNumericError
End If
If decEntertainment <= 0 Then
strEntertainment = InputBox(strEntertainmentInput, strEntertainmentHeading, " ")
End If
Loop Until IsNumeric(strEntertainment) And decEntertainment >= 0
答案 0 :(得分:0)
当然,你有这个问题:默认情况下decEntertainment为0,第二次请求输入后,你不再转换为.ToDecimal。
如果您采用明确的编码风格,例如
,则可以避免此类错误Do
strEntertainmentInput = ''
strEntertainment = InputBox(strEntertainmentInput, strEntertainmentHeading, " ")
If Not IsNumeric(strEntertainment) Then
strEntertainmentInput = strNonNumericError
Else
decEntertainment = Convert.ToDecimal(strEntertainment)
If decEntertainment < 0 Then
strEntertainmentInput = strNegativeError
Else
lstBudget.Items.Add("Entertainment Expense: " & decEntertainment.ToString("C2"))
End
End
Loop Until strEntertainmentInput = ''