如何让 InputBox 只接受数字
问题描述:
代码只是询问 6 所不同大学的通过率.比率必须是介于 1 和 100 之间的值.
The code is just asking for the pass rates for 6 different colleges. The rate must be a value between 1 and 100.
我希望它只允许数字.我曾尝试使用 IsNumeric
,但我一定没有正确使用它.这是我到目前为止所拥有的:
I would like it to only allow numbers. I have tried using IsNumeric
, but I must not be using it correctly. Here's what I have so far:
For i As Integer = 0 To 5
passRate(i) = InputBox("Enter the pass rate for " & colleges(i) & " college")
While passRate(i) > 100 Or passRate(i) < 0
MsgBox("Error must be a number and be between 0 and 100")
passRate(i) = InputBox("Enter the pass rate for " & colleges(i) & " college")
End While
Next i
答
使用此函数进行校验值
Private Function IsInputNumeric(input As String) As Boolean
If String.IsNullOrWhiteSpace(input) Then Return False
If IsNumeric(input) Then Return True
Dim parts() As String = input.Split("/"c)
If parts.Length <> 2 Then Return False
Return IsNumeric(parts(0)) AndAlso IsNumeric(parts(1))
End Function
并像这样使用
For i As Integer = 0 To 5
passRate(i) = InputBox("Enter the pass rate for " & colleges(i) & " college")
If IsInputNumeric(passRate(i)) Then
'handle numeric input
Else
'handle not a number
End If
While passRate(i) > 100 Or passRate(i) < 0
MsgBox("Error must be a number and be between 0 and 100")
passRate(i) = InputBox("Enter the pass rate for " & colleges(i) & " college")
End While