Test that data is numeric. Add range checks and other tests, as needed.
You have some data that's supposed to be numeric. Could be from a cell, a file, a dialog box, wherevs. You want to check the data.
A data value.
Number that's valid, or an error message.
An example:
- 'A temporary variable to hold unchecked user input.
- Dim tUncheckedUserInput as String
- Dim sMealCost As Single
- ...
- tUncheckedUserInput = Cell(x,y), InputBox(), Input#1..., wherevs.
- If Not IsNumeric(tUncheckedUserInput) Then
- MsgBox "Sorry, meal cost must be a number."
- End
- End If
- sMealCost = tUncheckedUserInput
- ' Range check.
- If sMealCost < 0 Then
- MsgBox "Sorry, meal cost cannot be negative."
- End
- End If
You need two variables. The first is a string, to hold the raw data you want to test. Strings can hold anything you can type, so there are no data mismatch errors, if the raw data is non-numeric.
You test whether the raw data is numeric (line 6). If it is not, show an error message (line 7), and stop the program (line 8).
If the raw data is numeric, you can safely move into a Single
variable (line 10). That's the variable you'll use for calculations later.
If you need other tests, add them. For example, in this case there's a range check, to make sure the value is more than zero (lines 12-15).