A regex based UDF. This is based on the currency being present as text i.e. has USD/EUR etc in the cell.
Option Explicit
Public Function GetCurrencySum(ByVal rng As Range, ByVal aCurrency As String) As Variant
Dim inputString As String, arr()
If rng.Columns.Count > 1 Then
GetCurrencySum = CVErr(xlErrNA)
Exit Function
End If
Select Case rng.Count
Case 1
ReDim arr(0): arr(0) = rng.Value
Case Else
arr = rng.Value
End Select
inputString = Join(Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Index(arr, 0, 1)), "~") & "~"
Dim matches As Object, match As Object
With CreateObject("VBScript.RegExp")
.Global = True
.MultiLine = True
.Pattern = "[+-]?" & aCurrency & ".*?(?=~)"
On Error GoTo errhand:
If .TEST(inputString) Then
Set matches = .Execute(inputString)
For Each match In matches
GetCurrencySum = GetCurrencySum + CDbl(Replace$(match, aCurrency, vbNullString))
Next
Exit Function
End If
GetCurrencySum = 0
Exit Function
End With
errhand:
GetCurrencySum = CVErr(xlErrNA)
End Function
In sheet:
Regex:
Try it here.
[+-]?JPY.*?(?=~)
/
gm
Match a single character present in the list below [+-]?
?
Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)
+-
matches a single character in the list +-
(case sensitive)
JPY
matches the characters JPY
literally (case sensitive) '
.*?
matches any character (except for line terminators)
*?
Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
Positive Lookahead (?=~)
Assert that the Regex below matches
~
matches the character ~
literally (case sensitive)
If there is other text in the cell then you could try:
Public Function GetCurrencySum(ByVal rng As Range, ByVal aCurrency As String) As Variant
Dim inputString As String, arr()
If rng.Columns.Count > 1 Then
GetCurrencySum = CVErr(xlErrNA)
Exit Function
End If
Select Case rng.Count
Case 1
ReDim arr(0): arr(0) = rng.Value
Case Else
arr = rng.Value
End Select
inputString = Join(Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Index(arr, 0, 1)), "~") & "~"
Dim matches As Object, match As Object
With CreateObject("VBScript.RegExp")
.Global = True
.MultiLine = True
.Pattern = "[\-\+]?" & aCurrency & "\s[\d,.]+"
On Error GoTo errhand:
If .test(inputString) Then
Set matches = .Execute(inputString)
For Each match In matches
GetCurrencySum = GetCurrencySum + CDbl(Replace$(Replace$(match, aCurrency, vbNullString), "~", vbNullString))
Next
Exit Function
End If
GetCurrencySum = 0
Exit Function
End With
errhand:
GetCurrencySum = CVErr(xlErrNA)
End Function
Try it here.
SUMIF
) but I'm not sure if this solution will work for you. – ImaginaryHuman072889