I've been struggelig with an embarrassing and annoying little problem in visual basic (I'm, as you probbably see, a beginner). The problem is the error message system for when letters are entered instead of numbers. I get "can't convert from integer to string.
Any help on this would be most appreciated.
Here is my code:
Dim number1, number2 As Integer
Dim sum As String
number1 = InputBox("first value:")
number2 = InputBox("second value:")
sum = number1 + number2
If IsNumeric(sum) Then
MsgBox("The sum of the numbers " & number1 & " and " & number2 & " is: " & sum)
ElseIf Not IsNumeric(sum) Then
MsgBox("You may only type numbers into the fields!, trie again")
End If
In advance, thank you :)!
You are doing the
Typeconversion wrongly. Improved code:InputBoxreturns strings which you are implicitely converting toIntegerby associating them to integer-type variables, thus you provoke an error when inputting non-numeric values. Best way to avoid problems is relying always on the right Type, as shown in the code above: the inputs are strings butIsNumerictakes precisely strings as inputs. Once the right inputs are confirmed, the conversion to the corresponding type (Integer, but you might want to rely onDecimalorDoubleto account for decimal positions) is performed and the mathematica operation performed with numeric types. Lastly, I am performing a conversion toString(just to keep this answer consistent), although bear in mind that VB.NET performs this conversion (from number to string) implicitely without any problem.