Excel VBA

Excel VBA
Excel Formulas
User-defined Functions
Office Links
Access VBA
Access SQL
Alan’s Excel FAQ
Excel Home
Alan’s Home

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
        Next
    Next
    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-2009

Updated:  11/16/2009 23:41
This page added:  03 June 2003