I am trying to code a search + sum engine on Excel VBA. I have a list of entries, and what I need the code to do is search for a specific type of cost (for example "1 Equipment") and then it needs to sum all Equipment Costs and print it in a cell in another worksheet. Heres what I typed so far:
Sub Sample()
Dim fnd As String
Dim MyAr
Dim i As Long
Dim rng As Range, FoundCell As Range, LastCell As Range, myRange As Range
Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)
fnd = "1 Equipment"
MyAr = Split(fnd, "/")
For i = LBound(MyAr) To UBound(MyAr)
Set FoundCell = myRange.Find(what:=MyAr(i), after:=LastCell)
If Not FoundCell Is Nothing Then
FirstFound = FoundCell.Address
End If
Set rng = FoundCell
Do Until FoundCell Is Nothing
Set FoundCell = myRange.FindNext(after:=FoundCell)
Set rng = Union(rng, FoundCell)
If FoundCell.Address = FirstFound Then Exit Do
Loop
If Not rng Is Nothing Then
rng.**(____in here it needs to sum the value of the cell in
the column to the right of where the word was found___)**
End If
Next i
End Sub
This is the picture of my list of values (I only have a few values typed, but the engine has to go all the way to the end of the worksheet): https://i.stack.imgur.com/ZPIc9.png It needs to sum all the "1 Equipment" values and display the sum in another cell, so for this amount of entries, the answer would be 11750.
I am a beginner with excel VBA so I really need help. Thank you!
I would do that more like a custom function to be added to the sheet where you find all the cells corresponding to a given value and you sum up the adjacent cell numbers:
Public Function SumInvestments(ByVal InvType As String) As Long
Dim allCells As Range
Dim singleCell As Range
Dim totalSum As Long
Set allCells = Range("A1:A" & Range("A1").End(xlDown).Row).Find(InvType, lookAt:=xlWhole)
If Not allCells Is Nothing Then
For Each singleCell In allCells
totalSum = totalSum + singleCell.Offset(0,1).Value
Next singleCell
End If
SumInvestments = totalSum
End Function
To be used like this:
=SumInvestments("1 Equipment")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.