2017-09-13 99 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()完成了。但非常感谢你的回答! –