我正在寻找一种方法让Excel找到一个实例的所有值,例如某个范围内的“ABC”,然后返回并求和相应的值。
我一直在研究这样做的VBA功能,但有更简单的方法吗?
谢谢!
答案 0 :(得分:2)
你看过SUMIF函数了吗?听起来这样会对你有所帮助。
答案 1 :(得分:2)
RobertMS是正确的,SUMIF函数将起作用:
ABC | 1
DEF | 1
ABC | 3
Sum of ABC | =SUMIF(A1:A3,"ABC",B1:B3)
如果你需要一个VBA函数来查找某个范围内的所有值,那么这样的东西会有所帮助:
Public Function FindAllInRange(Source As Range, Value As String) As Collection
Dim Result As New Collection
Dim CurCell As Range
Dim ColIndex As Long
Dim RowIndex As Long
Dim Address As String
' Iterate through columns then rows
For ColIndex = 1 To Source.Columns.Count
For RowIndex = 1 To Source.Rows.Count
Set CurCell = Source(RowIndex, ColIndex)
' Match the value (adjust this to your needs)
If CurCell.Value = Value Then
Address = CurCell.Worksheet.Name & "!" & CurCell.Address
Debug.Print "Found match '" & Value & "' at: " & Address
Result.Add CurCell, Address
End If
Next RowIndex
Next ColIndex
Set FindAllInRange = Result
End Function
Public Sub TestFindAllInRange()
Dim Result As Collection
Set Result = FindAllInRange(Selection, "ABC")
Debug.Print "Found " & Result.Count & " cells"
End Sub
如果符合您的需求,SUMIF会更容易。如果使用VBA函数,那么仍然需要对值进行求和。很容易获得结果集合的计数,但是您需要将结果处理为总和。