Checking a Range of Values

You may find at times that testing a value for a particular data type (such as number or string) is not enough to prevent input errors. Sometimes it is necessary to check for a range of values. For example, you may wish to prompt a user to enter a number from 1 to 100. Maybe you want a person to pick a letter from a to z.

Testing for a range of values involves a little more thought from the programmer. Specifically, your first thought should be to know the range(s) needing to be tested and if the ranges are numeric or character based. Testing ranges of values with numbers or strings uses the same programming constructs consisting of compound conditions.

Let's take the 1 to 100 example I mentioned earlier. As seen here, I continue to use the IsNumeric function as part of the overall testing for a range of numbers (1 to 100):

Private Sub cmdCheckRange_Click()

If IsNumeric(txtInput.Value) = True Then

If Val(txtlnput.Value) >= 1 And _ Val(txtlnput.Value) <= 100 Then

MsgBox "You entered a number between 1 and 100."


MsgBox "Your number is out of range." End If Else

MsgBox "Please enter a number from 1 to 100." End If End Sub

Testing for a range of letters (characters) is not much different, if you remember that all characters (letters or numbers) can be represented with ANSI (American National Standards Institute) values. For example, say I want a user to enter a letter in the range of a through m (including both upper- and lowercase letters within the range). I can still use the IsNumeric function to help me out, but I need to perform some additional tests.

Private Sub cmdCheckRange_Click()

If IsNumeric(txtlnput.Value) = False Then

If Asc(UCase(txtInput.Value)) >= 65 And _ Asc(UCase(txtInput.Value)) <= 77 Then

MsgBox "You entered a letter between a and m."


MsgBox "Your letter is out of range." End If


MsgBox "Please enter a letter between a and m." End If End Sub

In the preceding code, I'm looking for the IsNumeric function to return a False value, which means the input was not a number. Next I use the Asc function, which converts a character to its corresponding ANSI value.

Using compound conditions, I specifically look for an ANSI range between 65 and 77, the numbers that represent the capital letters A and M. You may also notice that I used the function UCase in association with the Asc function. The UCase function converts lowercase letters to uppercase letters. If I didn't convert the characters to uppercase, I would have needed to check for the lowercase letters as well (ANSI numbers 97 to 109).

0 0

Post a comment