Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Function to strip all other than numbers from a field 1

Status
Not open for further replies.

Moss100

Technical User
Aug 10, 2004
586
GB
Hello I have a field InvoiceNumber

The invoice data sometimes has prefix or postfix - ie. eet3546 or ibb876373 or 2355456llk

I would like a function which removes everything and just leaves the numbers with no spaces or other characters.

Could someone help with this? I really can't seem to make progress with this.

Thanks Mark - Keep safe :)
 
I am sure there is a better way, but ...

Code:
Option Explicit

Private Sub Command1_Click()
Dim str1 As String
Dim str2 As String
Dim str3 As String

str1 = "eet3546"
str2 = "ibb876373"
str3 = "2355456llk"

Debug.Print "The value of " & str1 & " is " & [blue]MyValue[/blue](str1)
Debug.Print "The value of " & str2 & " is " & [blue]MyValue[/blue](str2)
Debug.Print "The value of " & str3 & " is " & [blue]MyValue[/blue](str3)

End Sub
[blue]
Private Function MyValue(ByRef str As String) As Long
Dim x As Integer
Dim strOut As String

For x = 1 To Len(str)
    If IsNumeric(Mid(str, x, 1)) Then
        strOut = strOut & Mid(str, x, 1)
    End If
Next x

MyValue = CLng(strOut)

End Function[/blue]

You get:[tt]
The value of eet3546 is 3546
The value of ibb876373 is 876373
The value of 2355456llk is 2355456
[/tt]


---- Andy

There is a great need for a sarcasm font.
 
Thats great - thank you very much

Regards Mark
 
I have tested it - and it works well.

I notice it is fine if there is a 10 or less digit number, but it crashes if 11 digits or more.

Is there a way to fix that?

Thank you Mark
 
That is because of the limit of Long.

You could modify the Function to:

Code:
Private Function MyValue(ByRef str As String) [red]As Double[/red]
Dim x As Integer
Dim strOut As String

For x = 1 To Len(str)
    If IsNumeric(Mid(str, x, 1)) Then
        strOut = strOut & Mid(str, x, 1)
    End If
Next x

MyValue = [red]CDbl[/red](strOut)

End Function

But you may get back the huge number in scientific notation :)

You can simply do:

Code:
Private Function MyValue(ByRef str As String) [red]As String[/red]
Dim x As Integer
Dim strOut As String

For x = 1 To Len(str)
    If IsNumeric(Mid(str, x, 1)) Then
        strOut = strOut & Mid(str, x, 1)
    End If
Next x

MyValue = strOut

End Function

and you get the String with just the digits (numbers)... [wavey3]


---- Andy

There is a great need for a sarcasm font.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top