Try,
Это макрос UDF.
d5 = AverageSemester()
Ниже представлен макрос.
Sub Test()
Dim Ws As Worksheet
Dim Semester1 As Variant, Semester2 As Variant
Dim mySemester As Variant
Dim Target As Range, rngLast As Range
Dim s As String
Dim r As Integer, i As Integer
Semester1 = Array("May", "Jun", "Jul", "Aug", "Sep", "Oct")
Semester2 = Array("Nov", "Dec", "Jan", "Feb", "Mar", "Apr")
Set Ws = Sheets(1)
With Ws
r = .Range("c" & Rows.Count).End(xlUp).Row - 1
Set rngLast = .Range("b" & r).Offset(, 1)
s = .Range("b" & r)
If isSemes(s, Semester1) Then
mySemester = Semester1
Else
mySemester = Semester2
End If
For i = r To r - 12 Step -1
s = .Range("b" & i)
If isSemes(s, mySemester) Then
Set Target = .Range("b" & i).Offset(, 1)
Else
Exit For
End If
Next i
.Range("d5") = WorksheetFunction.Average(.Range(Target, rngLast))
End With
End Sub
Function isSemes(s As String, vSemester As Variant)
Dim v As Variant
For Each v In vSemester
If v = s Then
isSemes = True
Exit Function
End If
Next
End Function
Function AverageSemester()
Dim Ws As Worksheet
Dim Semester1 As Variant, Semester2 As Variant
Dim mySemester As Variant
Dim Target As Range, rngLast As Range
Dim s As String
Dim r As Integer, i As Integer
Application.Volatile
Semester1 = Array("May", "Jun", "Jul", "Aug", "Sep", "Oct")
Semester2 = Array("Nov", "Dec", "Jan", "Feb", "Mar", "Apr")
Set Ws = Sheets(1)
With Ws
r = .Range("c" & Rows.Count).End(xlUp).Row - 1
Set rngLast = .Range("b" & r).Offset(, 1)
s = .Range("b" & r)
If isSemes(s, Semester1) Then
mySemester = Semester1
Else
mySemester = Semester2
End If
For i = r To r - 12 Step -1
s = .Range("b" & i)
If isSemes(s, mySemester) Then
Set Target = .Range("b" & i).Offset(, 1)
Else
Exit For
End If
Next i
AverageSemester = WorksheetFunction.Average(.Range(Target, rngLast))
End With
End Function
Когда сентябрь - последние данные
Средний диапазон ~~> май, июнь, июль, август, сентябрь
Когда в январе последние данные
Средний диапазон ~~> ноябрь, январь