Urgent VB6 Question! Checking for numbers in string...
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!
If you can index individual characters of the string and get their character code, it is trivial.
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
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
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]
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]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement