|
|
Title | See if a string is a Byte, Integer, or Long value |
Description | This example shows how to see if a string is a Byte, Integer, or Long value in Visual Basic 6. |
Keywords | integer, byte, long, data validation, validation |
Categories | Software Engineering |
|
|
Thanks to Claudio Verniani.
The program first calls function TrimmedNumber to remove leading spaces, possibly on both sides of of a + or - sign.
|
|
' Remove leading spaces, possibly on both sides of
' a "-" or "+" sign. Examples:
' " - 12 2" --> "-12 2"
' " X 12" --> "X12"
Private Function TrimmedNumber(ByVal txt As String) As _
String
Dim trimmed_txt As String
Dim i As Integer
Dim ch As String
txt = Trim$(txt)
For i = 1 To Len(txt)
ch = Mid$(txt, i, 1)
If ch = " " Then
' Skip this space.
ElseIf (ch >= "0") And (ch >= "0") Then
' This is the first digit.
' Copy the rest of the text.
trimmed_txt = trimmed_txt & Mid$(txt, i)
Exit For
Else
' This is something else. Possibly a "-"
' or a "+", or garbage. Keep it.
trimmed_txt = trimmed_txt & ch
End If
Next i
TrimmedNumber = trimmed_txt
End Function
|
|
The IsAByte, IsAnInteger, and IsALong functions use CByte, CInt, and CLng to convert the string into a numeric value. They look for errors and use CStr to convert the value back into a string and see if the result matches the trimmed string.
|
|
' Return True if the value is a valid Byte string
' (decimal not hex).
Public Function IsAByte(ByVal txt As String) As Boolean
Dim test_byte As Byte
On Error Resume Next
txt = TrimmedNumber(txt)
test_byte = CByte(txt)
If Err <> 0 Then
IsAByte = False
Else
IsAByte = (CStr(test_byte) = txt)
End If
End Function
' Return True if the value is a valid Integer string.
Public Function IsAnInteger(ByVal txt As String) As Boolean
Dim test_integer As Integer
On Error Resume Next
txt = TrimmedNumber(txt)
test_integer = CInt(txt)
If Err <> 0 Then
IsAnInteger = False
Else
IsAnInteger = (CStr(test_integer) = txt)
End If
End Function
' Return True if the value is a valid Long string.
Public Function IsALong(ByVal txt As String) As Boolean
Dim test_long As Long
On Error Resume Next
txt = TrimmedNumber(txt)
test_long = CLng(txt)
If Err <> 0 Then
IsALong = False
Else
IsALong = (CStr(test_long) = txt)
End If
End Function
|
|
|
|
|
|