How to find numbers from a string? How to find numbers from a string? vba vba

How to find numbers from a string?


Assuming you mean you want the non-numbers stripped out, you should be able to use something like:

Function onlyDigits(s As String) As String    ' Variables needed (remember to use "option explicit").   '    Dim retval As String    ' This is the return string.      '    Dim i As Integer        ' Counter for character position. '    ' Initialise return string to empty                       '    retval = ""    ' For every character in input string, copy digits to     '    '   return string.                                        '    For i = 1 To Len(s)        If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then            retval = retval + Mid(s, i, 1)        End If    Next    ' Then return the return string.                          '    onlyDigits = retvalEnd Function

Calling this with:

Dim myStr as StringmyStr = onlyDigits ("3d1fgd4g1dg5d9gdg")MsgBox (myStr)

will give you a dialog box containing:

314159

and those first two lines show how you can store it into an arbitrary string variable, to do with as you wish.


Regular expressions are built to parse. While the syntax can take a while to pick up on this approach is very efficient, and is very flexible for handling more complex string extractions/replacements

Sub Tester()     MsgBox CleanString("3d1fgd4g1dg5d9gdg")End SubFunction CleanString(strIn As String) As String    Dim objRegex    Set objRegex = CreateObject("vbscript.regexp")    With objRegex     .Global = True     .Pattern = "[^\d]+"    CleanString = .Replace(strIn, vbNullString)    End WithEnd Function


Expanding on brettdj's answer, in order to parse disjoint embedded digits into separate numbers:

Sub TestNumList()    Dim NumList As Variant  'Array    NumList = GetNums("34d1fgd43g1 dg5d999gdg2076")    Dim i As Integer    For i = LBound(NumList) To UBound(NumList)        MsgBox i + 1 & ": " & NumList(i)    Next iEnd SubFunction GetNums(ByVal strIn As String) As Variant  'Array of numeric strings    Dim RegExpObj As Object    Dim NumStr As String    Set RegExpObj = CreateObject("vbscript.regexp")    With RegExpObj        .Global = True        .Pattern = "[^\d]+"        NumStr = .Replace(strIn, " ")    End With    GetNums = Split(Trim(NumStr), " ")End Function