我的数据放在一个范围内。如何得到一个列的平均值,多个条件是一个OR条件。在这个示例中,Temprange.columns(2)
应该是"高"或"少校"
这应该在不采用平均两个平均值的情况下完成,如下例所示:
Dim a As Long
Dim b As Long
Dim ObjectKeyCounter As Long
Dim TempRange As Range
Dim TempArr As Variant
Dim MyArray As Variant
a = Application.WorksheetFunction.AverageIfs(TempRange.Columns(20), _
TempRange.Columns(1), TempArr(ObjectKeyCounter), TempRange.Columns(2), "High")
b = Application.WorksheetFunction.AverageIfs(TempRange.Columns(20), _
TempRange.Columns(1), TempArr(ObjectKeyCounter), TempRange.Columns(2), "Major")
MyArray(1, 1) = Application.WorksheetFunction.Average(a, b)
出于某种原因,我无法在互联网上找到任何东西,所以我想我的方式(因此我的搜索)是错误的。
编辑:感谢Scott Holtzman,我的解决方案如下:
Function AverageIfsOr(ByRef TempArr_Dashboard As Variant, _
ByRef ObjectKeyCounter As Long, _
ByRef TempArr_Data As Range, _
ByRef ColumnToAvg As Long) As Double
Dim vAvg() As Variant
Dim vAvgCounter As Integer
Dim DataRowCounter As Integer
vAvgCounter = 0
For DataRowCounter = 1 To TempArr_Data.Rows.Count
If TempArr_Data(DataRowCounter, 4) = TempArr_Dashboard(ObjectKeyCounter) Then
If TempArr_Data(DataRowCounter, 11) = "High" Or TempArr_Data(DataRowCounter, 11) = "Major" Then
vAvgCounter = vAvgCounter + 1
ReDim Preserve vAvg(vAvgCounter)
vAvg(vAvgCounter) = TempArr_Data(DataRowCounter, ColumnToAvg)
End If
End If
Next DataRowCounter
If vAvgCounter = 0 Then
AverageIfsOr = 0
Else: AverageIfsOr = Application.WorksheetFunction.Average(vAvg)
End If
End Function
答案 0 :(得分:2)
可能有一种更简单的方法,但这有效。
Option Explicit
Sub AverageIfsOr()
Dim v As Variant
Dim vAvg() As Variant
v = Range("C4:E7")
Dim i As Integer
For i = 1 To UBound(v) - 1
If (v(i, 1) = "A" Or v(i, 1) = "B") And (v(i, 2) = "High" Or v(i, 2) = "Major") Then
ReDim Preserve vAvg(i)
vAvg(i) = v(i, 3)
End If
Next
MsgBox Application.WorksheetFunction.Average(vAvg)
End Sub
你可以玩If条件和恶心。
测试数据在这里: