View Single Post
  #14   Report Post  
Posted to microsoft.public.excel.misc
Rick Rothstein \(MVP - VB\)[_763_] Rick Rothstein \(MVP - VB\)[_763_] is offline
external usenet poster
 
Posts: 1
Default Adding numbers within cells that also contain words

If you do want to use a UDF, then:

<alt-F11 opens the VB Editor. Ensure your project is highlighted in the
project explorer window, then select Insert/Module and paste the code
below
into the window that opens.

To use this UDF, enter the formula:

=SumBags(range) into some cell where "range" represents where your data
might
be.

As written, the routine will extract the first integer (no decimals or
fractions) value from the string, regardless of location, and will sum all
of
that in the range.

===============================
Option Explicit
Function SumBags(rg As Range) As Double
Dim c As Range
Dim re As Object, mc As Object
Set re = CreateObject("vbscript.regexp")
re.Global = False
re.Pattern = "\d+"

For Each c In rg
If re.test(c.Value) = True Then
Set mc = re.Execute(c.Value)
SumBags = SumBags + mc(0).Value
End If
Next c

End Function


Just to keep the archive records complete, here is a non-RegEx UDF solution
that duplicates your results...

Function SumBags(R As Range) As Double
Dim X As Long
Dim C As Range
Dim Sum As Double
For Each C In R
For X = 1 To Len(C.Value)
If Mid(C.Value, X, 1) Like "#" Then
SumBags = SumBags + Val(Mid(Replace(C.Value, ".", "X"), X))
Exit For
End If
Next
Next
End Function

Rick