Page 141 - Excel Progamming Weekend Crash Course
P. 141
h540629 ch09.qxd 9/2/03 9:34 AM Page 116
116 Saturday Morning
Listing 9-1 Determining if a string represents a number
Public Function IsNumber(s As String) As Boolean
‘ Returns True if the argument is a number
‘ containing only the digits 0-9.
‘ Returns False otherwise.
Dim i As Integer
Dim buf As String * 1
IsNumber = True
‘ Return False if an empty string was passed.
If Len(s) = 0 Then
IsNumber = False
Exit Function
End If
‘ Loop thru all characters in s.
For i = 1 To Len(s)
‘ Extract the ith character.
buf = Mid(s, i, 1)
If Asc(buf) < 48 Or Asc(buf) > 57 Then
IsNumber = False
Exit For
End If
Next i
End Function
Public Sub TestIsNumber()
Dim str As String
Dim InputOK As Boolean
‘ The default for Boolean values is False,
‘ but it never hurts to explicitly initialize
‘ the value in code.
InputOK = False
Do
str = InputBox(“Please enter an integer number:”)
InputOK = IsNumber(str)
Loop Until InputOK
MsgBox “Thank you!”
End Sub