How to extract groups of numbers from a string in vba

This will run much faster than looping

Public Function NumericOnly(s As String) As String
    Dim s2 As String
    Dim replace_hyphen As String
    replace_hyphen = " "
    Static re As RegExp
    If re Is Nothing Then Set re = New RegExp
    re.IgnoreCase = True
    re.Global = True
    re.Pattern = "[^0-9 -]" 'includes space, if you want to exclude space "[^0-9]"
    s2 = re.Replace(s, vbNullString)
    re.Pattern = "[^0-9 ]"
    NumericOnly = re.Replace(s2, replace_hyphen)
End Function

Leave a Comment