我與斯科特認爲,在大多數情況下,公式是比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
結果應該是哪裏?新的工作表?同一張工作表?你如何計劃展示數十年? – LittleBobbyTables
您可以在沒有VBA的情況下執行此操作嗎?你想只有公式解決方案嗎?如果是這樣,告訴我你正在運行的XL版本。 –
使用帶有「按年分組」的SQL語句以及平均值,最大值和最小值來完成此操作將會很有幫助。您可以將Excel工作表導入到Access表中並執行此操作。我看到另一個類似的問題,如果您熟悉Access和SQL,可能會給您一些建議:http:// stackoverflow。com/questions/9226201/excel-vba-group-by-like-selection – kermit