2017-09-13 150 views
0

我想在Excel VBA上編碼搜索+總和引擎。我有一個條目列表,我需要的代碼是搜索特定類型的成本(例如「1 Equipment」),然後它需要總結所有設備成本並將其打印到另一個工作表中的單元格中。繼承人我所輸入到目前爲止:Excel VBA搜索+總和引擎

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 

這是我的價值觀清單的圖片(我只有幾個值類型,但發動機已經一路去到工作表的末尾): https://i.stack.imgur.com/ZPIc9.png 它需要總結所有的「1個設備」值,並在另一個單元格中顯示的總和,因此對於這一數額的條目,答案應該是11750.

我用Excel VBA初學者,所以我真的需要幫助。謝謝!

+0

和SUMIFS()是不夠的? –

+0

爲什麼要用「/」元素分割'fnd =「1 Equipment」'並創建一個數組?你正在尋找的是'fnd',所以'.Find(what:= fnd,after:= LastCell)' – danieltakeshi

+0

用SUMIFS完成了。謝謝! –

回答

0

我會做更多的像一個自定義的功能被添加到您找到與給定值的所有單元格,你總結了相鄰小區號碼錶:

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 

要用於像這個:

=SumInvestments("1 Equipment") 
+0

儘管我猜SUMIFS()是一個Excel內置函數也可以實現。 –

+0

是的,我用SUMIFS()完成了。但非常感謝你的回答! –