2016-07-24 69 views
0

當我運行我的代碼不止一次時,它將重複工作表中的結果。我需要刪除以前的數據,並在每次運行時粘貼新數據。使我的宏不重複結果

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 
+0

請提供數據 – EBH

+0

的一例我有數據的行中的一個具有時間(主片1/1/2016,13/2/2016,17/6/2016)我的代碼爲每個月創建工作表。當我運行我的代碼時,它會正常工作創建帶月份名稱的工作表,每個工作表包含本月的數據,但是當我再次運行它時,它將複製創建的工作表中的數據並創建另一個工作表範圍。我想要的是(如果工作表存在首先刪除表中存在的所有數據,然後將數據移動到工作表) – daniel

+0

你說_「行有日期」_但你的代碼循環通過一列...我假設日期在列「主數據表」的「C」,並粘貼到「SortTemp」 – user3598756

回答

0

我找到了解決辦法>>感謝對於所有

Option Explicit 

Sub CreateMonthlySheets() 
    Dim mMonth As Range 
    Dim shtName As String 
    Dim monthSht As Worksheet 
    Dim newSheet As Boolean 


' 'Turn off ScreenUpdating 
    Application.ScreenUpdating = False 
    'Make a copy of the data sheet and sort by date 

    With GetSheet("SortTemp", True, newSheet) '<-- get your "temp" sheet: if not existent then create it 
     If Not newSheet Then .Cells.Clear '<--| if it existed then clear it 
     Sheets("Main Data Sheet").UsedRange.Copy Destination:=.Cells(1, 1) '<--| fill it with "Main Data Sheet" sheet 

     '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" & .Cells(.Rows.Count, 1).End(xlUp).Row) 
      shtName = MonthName(Month(mMonth)) & Year(mMonth) '<--| build "month" sheet name 
      Set monthSht = GetSheet(shtName, False, newSheet) 'Set "month" sheet: if not existent then create it 
      monthSht.UsedRange.Offset(1).Clear 

     Next 


     For Each mMonth In .Range("C2:C" & .Cells(.Rows.Count, 1).End(xlUp).Row) 
      shtName = MonthName(Month(mMonth)) & Year(mMonth) '<--| build "month" sheet name 
      Set monthSht = GetSheet(shtName, False, newSheet) 'Set "month" sheet: if not existent then create it 
      ' monthSht.UsedRange.Offset(1).Clear 
      ' If newSheet Then '<--| if it didn't exist... 
       '...Copy Column Widths and Header Row 
       .Rows(1).Copy 
       monthSht.Rows(1).PasteSpecial Paste:=8 'ColumnWidth 
       monthSht.Rows(1).PasteSpecial   'Data and Formats 
     ' Else 'otherwise... 
       'monthSht.UsedRange.Offset(1).Clear '<--| ...clear it from row 2 downwards (assuming row 1 has at least one value...) 
     ' End If 
      'Copy Data 
      mMonth.EntireRow.Copy Destination:=monthSht.Cells(monthSht.Rows.Count, 1).End(xlUp).Offset(1) 
     Next 

    End With 
    'Delete SortTemp sheet 
    Application.DisplayAlerts = False 
    Sheets("SortTemp").Delete 
    Application.DisplayAlerts = True 
    'Turn on ScreenUpdating 
    Application.ScreenUpdating = True 
End Sub 


Function GetSheet(shtName As String, Optional okClear As Boolean = False, Optional newSheet As Boolean = False) As Worksheet 
    On Error Resume Next 
    Set GetSheet = Worksheets(shtName) 
    On Error GoTo 0 
    If GetSheet Is Nothing Then 
     newSheet = True 
     Set GetSheet = ActiveWorkbook.Sheets.Add(After:=Worksheets(Worksheets.Count)) 
     GetSheet.Name = shtName 
    Else 
     If okClear Then GetSheet.Cells.Clear 
     newSheet = False 
    End If 
End Function 
+0

你拿我的答案,張貼它,並標記爲您的解決方案?請讓事情恢復公平!謝謝 – user3598756

+0

很高興能夠爲嘗試和幫助你的人提供適當的反饋意見 – user3598756

0

試試這個

Option Explicit 

Sub CreateMonthlySheets() 
    Dim mMonth As Range 
    Dim shtName As String 
    Dim monthSht As Worksheet 
    Dim newSheet As Boolean 

' 'Turn off ScreenUpdating 
    Application.ScreenUpdating = False 
    'Make a copy of the data sheet and sort by date 
    With GetSheet("SortTemp", True, newSheet) '<-- get your "temp" sheet: if not existent then create it 
     If Not newSheet Then .Cells.Clear '<--| if it existed then clear it 
     Sheets("Main Data Sheet").UsedRange.Copy Destination:=.Cells(1, 1) '<--| fill it with "Main Data Sheet" sheet 

     '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" & .Cells(.Rows.Count, 1).End(xlUp).row) 
      shtName = MonthName(Month(mMonth)) & " " & Year(mMonth) '<--| build "month" sheet name 
      Set monthSht = GetSheet(shtName, False, newSheet) 'Set "month" sheet: if not existent then create it 
      If newSheet Then '<--| if it didn't exist... 
       '...Copy Column Widths and Header Row 
       .Rows(1).Copy 
       monthSht.Rows(1).PasteSpecial Paste:=8 'ColumnWidth 
       monthSht.Rows(1).PasteSpecial   'Data and Formats 
      Else 'otherwise... 
       monthSht.UsedRange.Offset(1).Clear '<--| ...clear it from row 2 downwards (assuming row 1 has at least one value...) 
      End If 
      'Copy Data 
      mMonth.EntireRow.Copy Destination:=monthSht.Cells(monthSht.Rows.Count, 1).End(xlUp).Offset(1) 
     Next 

    End With 
    'Delete SortTemp sheet 
    Application.DisplayAlerts = False 
    Sheets("SortTemp").Delete 
    Application.DisplayAlerts = True 
    'Turn on ScreenUpdating 
    Application.ScreenUpdating = True 
End Sub 

'Sub main() 
' Dim sh As Worksheet 
' Dim existent As Boolean 
' 
' Set sh = GetSheet("data1", False, existent) 
' 
'End Sub 

Function GetSheet(shtName As String, Optional okClear As Boolean = False, Optional newSheet As Boolean = False) As Worksheet 
    On Error Resume Next 
    Set GetSheet = Worksheets(shtName) 
    On Error GoTo 0 
    If GetSheet Is Nothing Then 
     newSheet = True 
     Set GetSheet = ActiveWorkbook.Sheets.Add(After:=Worksheets(Worksheets.Count)) 
     GetSheet.Name = shtName 
    Else 
     If okClear Then GetSheet.Cells.Clear 
     newSheet = False 
    End If 
End Function 

從結果:

  • 避免On Error Resume Next執政超過嚴格需要
  • 無需環路兩次
+0

親愛的@ user3598756,我的代碼創建範圍與月manes工作表時,我運行你的代碼它會給我錯誤在這個代碼'monthSht.Range(。行(2),.Rows(Rows.Count))。刪除'< - | ...從第2行向下清除...' – daniel

+0

將''刪除'變爲'清除'(參見編輯答案)。如果錯誤再次出現,請指定它是哪種錯誤 – user3598756

+0

請參閱編輯的代碼,其中我還更改了將「SortTemp」表單複製到「月份」表單中的語句 – user3598756