-1

I'm getting runtime error when I enter alphabets in the inputbox

Dim amount As String
        amount = InputBox("Enter the amount of people you want to participtate", "System Message")
        If amount < 0 Or Not (IsNumeric(amount)) Then
            MsgBox("Please enter positive number of people", vbExclamation, "System Message")
        End If
Chozo Qhai
  • 283
  • 2
  • 10
  • 19

3 Answers3

2

Comparing strings to numbers is pretty dangerous and blew up in your face. You can make it work but you'll have to code is carefully, ensuring that you never try to compare a string that can't be converted to a number. That requires using another operator:

    If Not IsNumeric(amount) OrElse amount < 0 Then
        MsgBox("Please enter positive number of people", vbExclamation, "System Message")
    End If

Note the changed order and the use of OrElse, the short-circuiting version of Or. It won't evaluate the right-hand side expression if the left-hand side is already True.

The more .NET centric way to do this is by using Integer.TryParse() to convert strings to numbers.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

To avoid an error, you can make it like this ..

If IsNumeric(amount) Then
  If value(amount) > 0 Then
    'codes here
  Else      
     MsgBox("Please enter positive number of people", vbExclamation, "System Message")
  End If
Else
  MsgBox("Please enter a number of people", vbExclamation, "System Message")
End If
matzone
  • 5,703
  • 3
  • 17
  • 20
0

So I was looking at validating a textbox, first I wanted to make sure that it was not empty and make sure that it was a number. I'm by no means an expert but I'll put the code I wrote to validate the user input. I put it in a function because I had a lot of text fields that the user had to enter.

Class MainWindow 
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    tb2.Text = tbCheck(tb1)
End Sub

Private Function tbCheck(ByRef tb As TextBox) As Boolean
    tbCheck = tb.Text.Length > 0
    Try
        tbCheck = (tb.Text / 1) > 0
    Catch ex As Exception
        tbCheck = False
    End Try
    Return tbCheck
End Function

End Class

This is just the simple program I wrote to check if the code worked as I had hoped. Hope this can help someone or at least tell me if there is something I'm missing.

dmshow
  • 121
  • 13