当我运行我的代码不止一次时,它将重复工作表中的结果。我需要删除以前的数据,并在每次运行时粘贴新数据。使我的宏不重复结果
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