使用VBA在列中查找值,然后在相邻列中求和

时间:2018-07-11 09:44:39

标签: excel vba excel-vba

我有一张这样的桌子:

<head>

实际表长约39000行。

所以我需要在 Name Variation Type No_of_unit_sold Apple FG72H 1 12 Apple FG72H 1 17 Apple FG72H 1 61 Apple FG73H 1 1 Apple FG74H 1 3 Orange OO20 1 3 Orange OO20 1 4 Orange OO20 1 117 Orange OO20 1 0 Orange OO20 1 4 Orange OO21 2 15 Grape G7TY 1 110 Grape G7TY 1 65 Grape G7TY 3 53 Grape G7TY 3 31 Grape G7TY 1 12 Grape G7TY 1 1 列中查找类型1(从1到32)

然后将相应的Type求和,并将结果放在No_of_unit_sold的底行。

No_of_unit_sold

我需要在Worksheets("All Fruits").Activate Dim i As Integer Dim rng As Range Worksheets(name).Activate lastrow = Range("C2").End(xlDown).Row For i = 1 to 32 Set rng = Range("D:D").Find(what = i) '??????????? Cells(lastrow, 5).Offset(1, 0).Select Cells(lastrow, 5).Offset(1, 0) = "=Sum(D2:D" & lastrow & ")" Next i End Sub 部分提出建议。

3 个答案:

答案 0 :(得分:2)

您只能使用公式来执行此操作(不需要VBA)。

假设您的示例中的数据为Type是C列,而No_of_unit_sold是D列。您可以在E列中使用:

=SUMIF(C:C,1,D:D)  'to sum all units of type 1
=SUMIF(C:C,2,D:D)  'to sum all units of type 2
…
=SUMIF(C:C,32,D:D) 'to sum all units of type 32

或者在下面的示例中我在G中使用的是:

=SUMIF(C:C,F:F,D:D)

请注意,您需要将结果放入新列中,而不要与No_of_unit_sold放在同一列中,因为这样会导致错误的计算。

enter image description here

答案 1 :(得分:1)

正如@Pᴇʜ所说,最好的解决方案是纯SUMIF。不需要VBA。

如果出于任何原因需要使用VBA进行操作,则使用Application.WorksheetFunction Property时,Excel中始终存在每个公式的VBA版本。

对于我的代码,我使用了WorksheetFunction.SumIf method

如果No_of_unit_sold,我的代码会弹出一个Msgbox,其总和为Type=1

Sub Macro1()
Dim LastRow As Long 'to save the last row number of column TYPE with data

LastRow = Range("C" & Range("C:C").Rows(Range("C:C").Rows.Count).Row).End(xlUp).Row

MsgBox Application.WorksheetFunction.SumIf(Range("C2:C" & LastRow), 1, Range("D2:D" & LastRow))
End Sub

根据您的需求进行调整。

答案 2 :(得分:0)

请尝试以下代码。使用if条件检查条件,然后从D列获取相应的值并将其添加到最终的Total

Sub Typee()

Dim TotalType As Integer
Dim Total As Integer
Total = 0

TotalType = Range("C2").End(xlDown).Row

For i = 2 To TotalType
If Sheets("Sheet1").Range("C" & i).Value = 1 Then
Total = Total + Sheets("Sheet1").Range("D" & i).Value
End If
Next

MsgBox Total

End Sub