code to find a number within a string

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I want to search a string for the first occurance of a number. Like the
string "John Q. Public - 300 Apple Street".
My VB is very rusty especially what functions to use; have not touched
Access in over a year and lost a hard drive to boot.
Thanks for your assistance.
 
Do you want code that return the first location of the number within the
string or the all number?
Can there be more then one number?
 
I'm assuming that the result you want is the complete number, 300 in your
example, rather than just the fist digit (3 in your example). Given that
assumption ...

Public Function FirstNumber(ByVal StringIn As String) As String

Dim StringOut As String
Dim lngChar As Long
Dim strChar As String
Dim boolDigitFound As Boolean

Const strcDigits As String = "1234567890"

For lngChar = 1 To Len(StringIn)
strChar = Mid$(StringIn, lngChar, 1)
If InStr(1, strcDigits, strChar) <> 0 Then
boolDigitFound = True
StringOut = StringOut & strChar
Else
If boolDigitFound = True Then
Exit For
End If
End If
Next lngChar
FirstNumber = StringOut

End Function
 
Yes, I need the location of the number within the string so that I can go
beyond the number and pick out other things in the string. Yes, there may be
more than one number.
Thanks.
 
In that case, you can take the function that Brendan gave you and modify it
to, and if there is no match it will return 0

Public Function FirstLocation(ByVal StringIn As String) As Number

Dim lngChar As Long
Dim strChar As String

Const strcDigits As String = "1234567890"

For lngChar = 1 To Len(StringIn)
strChar = Mid$(StringIn, lngChar, 1)
If InStr(1, strcDigits, strChar) <> 0 Then
FirstLocation = lngChar
Exit Function
End If
Next lngChar
FirstLocation = 0

End Function

I didn't try it, but I hope it will work
 
herb said:
I want to search a string for the first occurance of a number. Like the
string "John Q. Public - 300 Apple Street".


Here's an air code function to look for the first decimal
digit in a string:

Public Function FindDigit(strText As String) As Long
Dim lngLen As Long

For FindDigit = 1 To Len(strText)
If Mid(strText, FindDigit, 1) >= "0" _
And Mid(strText, FindDigit, 1) <= "9" Then
Exit For
End If
Next FindDigit
If FindDigit > Len(strText) Then FindDigit = 0
Exit Function
 
Back
Top