我想根据合约的长度对合约的净值进行平均,然后将平均值放在相应的合约长度Column G
旁边。需要求平均值的值为Column E
,合约长度为Column D
。因此,对于3年内合同的平均值将放在G5
中,依此类推。提前谢谢。
With Worksheets("Data")
Dim wf As WorksheetFunction
Dim rngNV As Range, Clength As Range
Set rngNV = .Range("E2", .Range("E2").End(xlDown))
Set Clength = .Range("D2", .Range("D2").End(xlDown))
.Range("G2") = wf.AverageIf(rngNV, Clength = 0)
.Range("G3") = wf.AverageIf(rngNV, Clength = 1)
.Range("G4") = wf.AverageIf(rngNV, Clength = 2)
.Range("G5") = wf.AverageIf(rngNV, Clength = 3)
.Range("G6") = wf.AverageIf(rngNV, Clength = 4)
.Range("G7") = wf.AverageIf(rngNV, Clength = 5)
.Range("G8") = wf.AverageIf(rngNV, Clength = 6)
.Range("G9") = wf.AverageIf(rngNV, Clength = 7)
.Range("G10") = wf.AverageIf(rngNV, Clength = 8)
.Range("G11") = wf.AverageIf(rngNV, Clength = 9)
.Range("G12") = wf.AverageIf(rngNV, Clength = 10)
.Range("G13") = wf.AverageIf(rngNV, Clength = 11)
.Range("G14") = wf.AverageIf(rngNV, Clength > 11)
End With
答案 0 :(得分:1)
Excel AVERAGEIF
函数有三个参数:
因此,您需要使用代码来使用
等语句.Range("G2") = Application.AverageIf(Clength , 0, rngNV)
但是你的代码可以放入一个循环来保存一些编码:
With Worksheets("Data")
Dim rngNV As Range, Clength As Range
Dim i As Long
Set rngNV = .Range("E2", .Range("E2").End(xlDown))
Set Clength = .Range("D2", .Range("D2").End(xlDown))
For i = 2 To 13
.Cells(i, "G") = Application.AverageIf(Clength, .Cells(i, "F"), rngNV)
Next
.Cells(14, "G") = Application.AverageIf(Clength, ">" & .Cells(13, "F"), rngNV)
End With
而且,如果第一列只是CountIf
,那么可以同时完成:
With Worksheets("Data")
Dim rngNV As Range, Clength As Range
Dim i As Long
Set rngNV = .Range("E2", .Range("E2").End(xlDown))
Set Clength = .Range("D2", .Range("D2").End(xlDown))
For i = 2 To 13
.Cells(i, "G") = Application.AverageIf(Clength, .Cells(i, "F"), rngNV)
.Cells(i, "I") = Application.CountIf(Clength, .Cells(i, "F"))
Next
.Cells(14, "G") = Application.AverageIf(Clength, ">" & .Cells(13, "F"), rngNV)
.Cells(14, "I") = Application.CountIf(Clength, ">" & .Cells(13, "F"))
End With