當我運行我的代碼不止一次時,它將重複工作表中的結果。我需要刪除以前的數據,並在每次運行時粘貼新數據。使我的宏不重複結果
Sub CreateMonthlySheets()
Dim lastRow, mMonth, tstDate1, tstDate2, shtName, nxtRow
On Error Resume Next
'Turn off ScreenUpdating
Application.ScreenUpdating = False
'Make a copy of the data sheet and sort by date
Sheets("Main Data Sheet").Copy After:=Sheets(1)
Sheets(2).Name = "SortTemp"
With Sheets("SortTemp")
lastRow = .Cells(Rows.Count, 1).End(xlUp).Row
Rows("2:" & lastRow).Sort Key1:=Range("C2"), Order1:=xlAscending
'Using SortTemp Sheet, create monthly sheets by
'testing Month and Year values in Column A
'Loop through dates
For Each mMonth In .Range("C2:C" & lastRow)
tstDate1 = Month(mMonth) & Year(mMonth)
tstDate2 = Month(mMonth.Offset(-1, 0)) & Year(mMonth.Offset(-1, 0))
'If Month and Year are different than cell above, create new sheet
If tstDate1 <> tstDate2 Then
ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
'Name the sheet based on the Month and Year
ActiveSheet.Name = MonthName(Month(mMonth)) & " " & Year(mMonth)
'Copy Column Widths and Header Row
.Rows(1).Copy
ActiveSheet.Rows(1).PasteSpecial Paste:=8 'ColumnWidth
ActiveSheet.Rows(1).PasteSpecial 'Data and Formats
End If
Next
On Error GoTo 0
'Loop through dates, copying row to the correct sheet
For Each mMonth In .Range("C2:C" & lastRow)
'Create sheetname variable
shtName = MonthName(Month(mMonth)) & " " & Year(mMonth)
'Determine next empty row in sheet
nxtRow = Sheets(shtName).Cells(Rows.Count, 1).End(xlUp).Row + 1
'Copy Data
.Range(mMonth.Address).EntireRow.Copy Destination:=Sheets(shtName).Cells(nxtRow, 1)
Next
End With
'Delete SortTemp sheet
Application.DisplayAlerts = False
Sheets("SortTemp").Delete
Application.DisplayAlerts = True
'Turn on ScreenUpdating
Application.ScreenUpdating = True
End Sub
請提供數據 – EBH
的一例我有數據的行中的一個具有時間(主片1/1/2016,13/2/2016,17/6/2016)我的代碼爲每個月創建工作表。當我運行我的代碼時,它會正常工作創建帶月份名稱的工作表,每個工作表包含本月的數據,但是當我再次運行它時,它將複製創建的工作表中的數據並創建另一個工作表範圍。我想要的是(如果工作表存在首先刪除表中存在的所有數據,然後將數據移動到工作表) – daniel
你說_「行有日期」_但你的代碼循環通過一列...我假設日期在列「主數據表」的「C」,並粘貼到「SortTemp」 – user3598756