Is there a VBA command that will turn a string of letters and numbers into just a number?

dan7055

Active Member
Joined
Jul 9, 2015
Messages
312
For example, is there a command I can use that will turn '62W' into the integer 62? It would also turn the integer 101 into 101. Basically it just drops any letters out of the string.
 

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type
You could do this. Keep in mind that all the other characters will be removed as well, so if your text is "A4556.56BH", this will result in 455656

Code:
Function StripChar(aText As String)
    Dim I As Integer


    StripChar = ""
    For I = 1 To Len(aText)
        aChar = Mid(aText, I, 1)
        Select Case aChar
            Case "0" To "9"
                StripChar = StripChar & aChar
        End Select
    Next
End Function






Sub macroName()


    Dim txt As String
    txt = "How is 123 a number?"
    finalnumber = Int(StripChar(txt))
    
End Sub
 
Upvote 0
Another way:

This is a variation on a function written by Rick Rothstein.

I've always been rather fond of it. It does not require concatenation.

Please note that it will return a string of text "numbers". If you aren't aware of it putting a "--" preceding the function call in the workbook will coerce the text into actual numeric values. The downside is you will lose any leading zeros and of course any decimals.

Code:
Function DigitsOnly(ByVal s As Variant) As Variant 'by Rick Rothstein
Dim i As Long

For i = 1 To Len(s)
If Mid(s, i, 1) Like "[!0-9]" Then Mid(s, i, 1) = Chr(1)
Next i

DigitsOnly = Replace(s, Chr(1), "")

End Function
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,975
Messages
6,122,538
Members
449,088
Latest member
RandomExceller01

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top