【发布时间】:2021-03-10 02:33:57
【问题描述】:
我正在尝试计算多个范围的平均值,如附图所示。 条件 - 它应该将“L”和“M”列的单元格值与“A”列的范围相匹配,并创建一个范围(例如 322810 到 324900)以计算针对特定范围的 B 列值的平均值(例如 322810到 324900)。 我已经能够编写以下代码,但它显然无法正常工作。
Dim lastrow As Long
Dim i As Long, j As Long
With Worksheets("Source")
lastrow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastrow + 1 'loop whole range (column C)
If .Cells(i, "L") = .Range("A").Value Then 'If column L cell value match with any cell of Range "A"
For j = i To lastrow 'Loop "group" range.
If .Cells(j, "M") = .Range("A").Value Then ' (end of small group range) then apply formula
.Cells(i, "N").Formula = "=AVERAGE(B" & i & ":B" & j & ")" 'AVG
Exit For
End If
Next j
End If
Next I
End With
【问题讨论】:
-
使用 AVERAGEIFS 并跳过 VBA。