# Urgent VB6 Question! Checking for numbers in string...

## Recommended Posts

gandolf1212    100
My final in VB6 is due in 2 hours! It's supposed to be able to make sure a string contains only letters, but I don't know how to check. Also, how could I check to see if a string was all numbers? Thanks!

##### Share on other sites
Fruny    1658
If you can index individual characters of the string and get their character code, it is trivial.

##### Share on other sites
gandolf1212    100
Sounds good.

So, if my string was txtFirstName, how would that look?

##### Share on other sites
Wan    1366

Private Sub Sample()    Dim txtFirstName As String    Dim i As Long    Dim liAsc As Byte        txtFirstName = "gandolf1212"        For i = 1 To Len(txtFirstName)        liAsc = Asc(Mid(txtFirstName, i, 1))        If liAsc >= 48 And liAsc <= 57 Then            ' it's a number!!            MsgBox "text contains numbers", vbOKOnly            Exit Sub        End If    Next i        MsgBox "text contains no numbers", vbOKOnlyEnd Sub

##### Share on other sites
DinGY    204
This is code from WanMaster, but i make some change.

Private Sub Sample()    Dim txt As String        txt = "gandolf1212"        For i = 1 To Len(txt)        If IsNumeric(Mid(txt, i, 1)) Then            MsgBox "text contains numbers", vbOKOnly            Exit Sub        End If    Next i        MsgBox "text contains no numbers", vbOKOnlyEnd Sub

##### Share on other sites
ahw    263
I dont mean to be annoying but you guys gave him wrong answers.
That is, your code is correct, but it doesnt answer the question:
"does the string contains ONLY letters"

So like you have done, but for each element in the string,
if the element is NOT A LETTER then you can stop examining the string and return an error

something like
function isAlpha( str as String ) as Boolean   isAlpha = True   If ( Asc(c) < Asc("A") ) Or _      ( ( Asc(c) > Asc("Z") ) And ( Asc(c) < Asc("a") ) ) Or _      ( Asc(c) > Asc("z") ) Then      isAlpha = False      exit function   End ifend function

The function will return true (the string is only made out of letters) unless
the if condition is fulfilled.
If you dont understand the if condition (i suggest you look up the ASCII values of letters, say in CHARMAP.exe)
If you dont understand THAT... you probably didnt deserve our help.
Or you can ask for an explanation [rolleyes]