Excel VBA

css navigation by Css3Menu.com

Count Numeric Values in String

The string can be any combination of numbers and letters. My client wanted to COUNT the numbers, not sum them
Public X As Long, Y As Long, D As Long, G As Variant

Sub CountNumbers()
    D = 0
    Range("A4").Select  'Get cell
    For X = 1 To Len(Cells(4, 1))   'build outside loop
        G = Mid(Cells(4, 1), X, 1)  'Get character to compare
            For Y = 0 To 9 Step 1   'Get numbers to count
                If Y = G Then       'Compare string
                    D = D + 1       'Count
                End If              'End
    Range("A4") = D         'Write answer
End Sub

After building as a macro, I decided that a User-defined function would be more useful so it is also available.

© 2003-2017

Updated:  06/14/2017 17:53
This page added:  03 June 2003