Search code examples
excelvbastringnumbers

excel vba keep only numbers in string


I have this code that gets whatever is on the clipboard and removes several characters.
But recenty these characters also became alphacaracters too.
I came across this code that REMOVES the numbers but I want to is just simply keep ~only~ the numbers, its inverse.

I did a lot of googleing and could not figure it out.

    Dim x
    Dim tmp As String
    tmp = input1
    'remove numbers from 0 to 9 from input string
    For x = 0 To 9
        tmp = Replace(tmp, x, "")
    Next
    'return the result string
    removenumbers = tmp  

My current code does this:

Sub y_chave_danfe()

    On Error GoTo ER2

    Dim atransf As New MSForms.DataObject
    Dim chave As Variant
    Dim danfe As Variant

    atransf.GetFromClipboard
    chave = atransf.GetText
    danfe = Replace(Replace(Replace(Replace(Replace(chave, " ", ""), "/", ""), "-", ""), ".", ""), "_", "")
    CreateObject("htmlfile").parentWindow.clipboardData.setData "text", danfe

Exit Sub

ER2:
End Sub

Solution

  • A simple method is by using Regular Expressions in a function. Merely pass the string to this function, at it will remove all of the non-digits:

    Function removeNonDigits(str As String) As String 'or as long, if you prefer
        Dim re As Object
        
    Set re = CreateObject("vbscript.regexp")
    With re
        .Pattern = "\D+"
        .Global = True
        removeNonDigits = .Replace(str, "")
    End With
    End Function
    

    If you don't want to use Regular Expressions, you can loop through the string:

    Function removeNonDigits(str As String) As String
        Dim I As Long
        Dim tmp As String
    
    tmp = ""
    For I = 1 To Len(str)
        If IsNumeric(Mid(str, I, 1)) Then
            tmp = tmp & Mid(str, I, 1)
        End If
    Next I
    
    removeNonDigits = tmp
    End Function