Input number as string

Situation: 

You want a user to input a number. You want to make sure it's a valid number, and give an error message if it isn't.

Actions: 

Put the user's input into a string variable. Test whether the variable has something that could be interpreted as a valid number. If so, convert the string into a number.

Explanation: 

If a user enters text, and you try to store it into a numeric variable, your program may crash. Input the data into a string variable first. An example:

  1. Dim userInput As String
  2. Dim numericVar as Single
  3. Dim errorFlag as Boolean
  4. errorFlag = True
  5. userInput = InputBox(prompt)
  6. If userInput = "" Then
  7.     errorFlag = True
  8. ElseIf Not IsNumeric(userInput) Then
  9.     errorFlag = True
  10. End If
  11. If errorFlag Then
  12.     'Do something
  13. Else
  14.     numericVar = Val(userInput)
  15. End If
Input goes into a string variable on line 5. Tests on lines 6 and 8 make sure it's numeric. It's converted into a number on line 14.