您還沒有說過是否有其他表沒有數據,或者數據出現在哪些列中。我已經假設數據總是在列A:B中,並且工作簿中沒有其他任何內容除了那些牀單。
這段代碼每次都會創建一個新的報告表 - 運行兩次它會崩潰,因爲它會嘗試創建名爲「報告」的第二個表(因此每次刪除報告表)。 有可能有更好的方法來做到這一點,這個代碼可以絕對改善,以滿足您的需求。
Public Sub Report()
Dim wrkSht As Worksheet
Dim wrkSht_rpt As Worksheet
Dim lLastRow As Long
Dim lLastRow_rpt As Long
'Create a new sheet to put the report on.
Set wrkSht_rpt = Worksheets.Add
wrkSht_rpt.Name = "Report"
'Get the data from each sheet and paste into columns A:B on the report sheet.
For Each wrkSht In ThisWorkbook.Worksheets
lLastRow = 0
With wrkSht
If .Name <> wrkSht_rpt.Name Then
'If there's no data in column A this will throw an error.
On Error Resume Next
lLastRow_rpt = wrkSht_rpt.Columns(1).Find("*", , , , xlByColumns, xlPrevious).Row
lLastRow = .Columns(1).Find("*", , , , xlByColumns, xlPrevious).Row
On Error GoTo 0
If lLastRow > 0 Then
'There's data on the sheet, so copy it to the report sheet.
.Range(.Cells(1, 1), .Cells(lLastRow, 2)).Copy _
Destination:=wrkSht_rpt.Cells(lLastRow_rpt + 1, 1)
End If
End If
End With
Next wrkSht
lLastRow = 0
lLastRow_rpt = 0
With wrkSht_rpt
'Find last row in column A on report.
lLastRow_rpt = .Columns(1).Find("*", , , , xlByColumns, xlPrevious).Row
'Copy all flavours to column D.
.Range(.Cells(1, 1), .Cells(lLastRow_rpt, 1)).Copy _
Destination:=.Cells(1, 4)
'Sort the column, this will place all blanks at the bottom.
.Sort.SortFields.Clear
.Sort.SortFields.Add Key:=.Range(.Cells(1, 4), .Cells(lLastRow_rpt, 4)), Order:=xlAscending
.Sort.SetRange .Range(.Cells(1, 4), .Cells(lLastRow_rpt, 4))
.Sort.Header = xlNo
.Sort.SortMethod = xlPinYin
.Sort.Apply
'Remove duplicates and find new last row in column D.
'The new last row is stored in a separate variable as we need to original to use
'within the SUMIF formula.
.Range(.Cells(1, 4), .Cells(lLastRow_rpt, 4)).RemoveDuplicates 1, xlNo
lLastRow = .Columns(4).Find("*", , , , xlByColumns, xlPrevious).Row
'Add a formula to add everything up, then copy paste values.
With .Range(.Cells(1, 5), .Cells(lLastRow, 5))
.FormulaR1C1 = _
"=SUMIF(R1C1:R" & lLastRow_rpt & "C1,RC4,R1C2:R" & lLastRow_rpt & "C2)"
.Copy
.PasteSpecial xlPasteValues
End With
.Range("A1:C1").EntireColumn.Delete
.Columns(1).AutoFit
End With
End Sub
真棒,感謝您花時間。我很少使用excel來處理簡單的電子表格。我知道它非常強大,現在我在學校學習C++,我認爲我應該讓excel爲我做好工作。 – liftedplane