我同意 Scott 的观点,在大多数情况下,公式是比 VBA 更好的选择。但是,您要求一些具体的事情,包括对数据进行排序,在单独的选项卡上显示结果,所以我假设在这种情况下,您可以接受宏带来的额外开销。
您遗漏了有关数据的一些详细信息(数据类型、特定单元格位置等)......所以请参阅代码中的注释,您可能需要自定义。
我试图尽可能按字面意思回答您的问题...例如,我个人可能更喜欢表格中的结果而不是横着的结果,但这不是我接近答案的方式。
Sub SummarizeDecade()
Const YearColumn As Integer = 2 'assumes the first year is in cell B2
Const FirstDataRow As Integer = 2 'assumes the first year is in cell B2
Dim wb As Excel.Workbook, ws As Excel.Worksheet, wsNew As Excel.Worksheet
Dim rowStart As Long, rowEnd As Long, colPaste As Long
Dim decade As Integer
Dim avg As Double, mini As Double, maxi As Double 'you didn't specify data type, Double is most accommodating
Set wb = ThisWorkbook
Set ws = wb.ActiveSheet 'assumes you run the macro while the data sheet is the current sheet; would prefer to use a sheet name
'setup new worksheet for summary results, as requested
wb.Worksheets.Add
Set wsNew = wb.Worksheets(1)
wsNew.Name = "Results"
wsNew.Cells(1, 1).Value = "Decade"
wsNew.Cells(2, 1).Value = "Average"
wsNew.Cells(3, 1).Value = "Minimum"
wsNew.Cells(4, 1).Value = "Maximum"
colPaste = 2
ws.Activate
ws.Cells(FirstDataRow, YearColumn).Sort ws.Cells(FirstDataRow, YearColumn), xlAscending, , , , , , xlYes 'sorts the data by year, as requested
rowStart = FirstDataRow
rowEnd = rowStart
Do Until Len(ws.Cells(rowEnd, 3).Value) = 0 'be sure your data does not include strings with spaces, zeroes, etc. Must be blank/null/empty.
decade = Int(ws.Cells(rowStart, YearColumn) / 10) * 10
Do Until Int(ws.Cells(rowEnd, YearColumn) / 10) * 10 <> decade
rowEnd = rowEnd + 1
Loop
'calculate the average, max, and min
avg = Application.WorksheetFunction.Average(ws.Range(ws.Cells(rowStart, 3), ws.Cells(rowEnd - 1, 3)))
mini = Application.WorksheetFunction.min(ws.Range(ws.Cells(rowStart, 3), ws.Cells(rowEnd - 1, 3)))
maxi = Application.WorksheetFunction.max(ws.Range(ws.Cells(rowStart, 3), ws.Cells(rowEnd - 1, 3)))
'write the summaries on the new worksheet tab
wsNew.Cells(1, colPaste).Value = decade
wsNew.Cells(2, colPaste).Value = avg
wsNew.Cells(3, colPaste).Value = mini
wsNew.Cells(4, colPaste).Value = maxi
colPaste = colPaste + 1
rowStart = rowEnd
Loop
End Sub