[英]Sum values on column A based on a string criteria in column B
我有以下列:
A B
23 75001
42 94
1 13
3 75002
4 12
如果 B 列中數字的前兩個數字與75
或12
匹配,我想對 A 列的值求和。
在此示例中,結果將是23 + 3 + 4
= 30
。
我嘗試使用=SUMIFS
但看起來我只能使用基於 integer 的標准...
你知道怎么做嗎?
編輯:我正在嘗試制作 VBA 宏
使用 SUMPRODUCT 的一種選擇:
=SUMPRODUCT(A1:A5*((--LEFT(B1:B5,2)=75)+(--LEFT(B1:B5,2)=12)))
同樣,如果您有權訪問它,請使用FILTER
:
=SUM(FILTER(A1:A5,((--LEFT(B1:B5,2)=75)+(--LEFT(B1:B5,2)=12))))
更短:
=SUMPRODUCT(A1:A5*(LEFT(B1:B5,2)={"75","12"}))
或者如果您不想在數字周圍加上引號
=SUMPRODUCT(A1:A5*(--LEFT(B1:B5,2)={75,12}))
但是,如果 B1:B5 中有一個或多個空白單元格,則將引號保持在75
和12
左右是更好的方法。
你可以使用:
=SUMPRODUCT(IF(ISNUMBER(SEARCH({"|75";"|12"},"|"&B1:B5)),A1:A5,0))
不過,如果您有 ExcelO365,則可以改用SUM()
。 如果你需要它是 VBA 你可以很容易地模仿這個。 不要誤會,另一個答案是首選方法,但是,如果需要,您可以輕松添加更多標准。
為了在 VBA 中模仿這一點,如果您將來需要添加更多標准,您可以使用數組和Select Case
:
Sub Test()
Dim lr As Long, x As Long, sm As Double, arr As Variant
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
With ws
lr = .Cells(.Rows.Count, 2).End(xlUp).Row
arr = .Range("A1:B" & lr).Value
For x = LBound(arr) To UBound(arr)
Select Case Left(arr(x, 2), 2)
Case "75", "12": sm = sm + arr(x, 1)
End Select
Next
Debug.Print sm
End With
End Sub
請嘗試下一個 function,請:
Function countOccLeft(arr As Variant, Cr1 As String, Cr2 As String) As Long
Dim dict As Object, i As Long: Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(arr)
If Left(arr(i, 2), 2) = Cr1 Or Left(arr(i, 2), 2) = Cr2 Then
If Not dict.Exists("key_sum") Then
dict.Add "key_sum", arr(i, 1)
Else
dict("key_sum") = dict("key_sum") + arr(i, 1)
End If
End If
Next i
countOccLeft = dict("key_sum")
End Function
可以這樣調用:
Sub testCountOccL()
Dim sh As Worksheet, arr As Variant, strSearch As String, lastRow As Long
Set sh = ActiveSheet
lastRow = sh.Range("A" & Rows.Count).End(xlUp).Row
arr = sh.Range("A2:B" & lastRow).Value
Debug.Print countOccLeft(arr, "75", "12")
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.