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

Started by
4 comments, last by ahw 18 years, 11 months ago
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!
I think there's to much blood in my caffeine system.
Advertisement
If you can index individual characters of the string and get their character code, it is trivial.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Sounds good.

So, if my string was txtFirstName, how would that look?
I think there's to much blood in my caffeine system.
I really shouldn't be doing your homework.. [headshake]

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
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

DinGY
Yesterday is history.Tomorrow is a mystery. Today is a gift"
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]
-----------------------------Sancte Isidore ora pro nobis !

This topic is closed to new replies.

Advertisement