2015-09-14 31 views
0

我已經運行這個宏,但它正在複製每個可用的工作表,即使我提到不要複製特定的工作表。將多個表格合併爲一個排除幾張表。錯誤

Sub Combine() 

Dim J As Integer 
Dim ws As Worksheet 

On Error Resume Next 

If ws.Name <> "Invoicing" And ws.Name <> "Master Data" Then 
    Sheets(1).Select 
    Worksheets.Add 
    Sheets(1).Name = "Combined" 
    Sheets(2).Activate 
    Range("A1").EntireRow.Select 
    Selection.Copy Destination:=Sheets(1).Range("A1") 
End If 
For J = 2 To Sheets.Count 
    Sheets(J).Activate 
    Range("A1").Select 
    Selection.CurrentRegion.Select 
    Selection.Offset(1, 0).Resize(Selection.Rows.Count - 1).Select 
    Selection.Copy Destination:=Sheets(1).Range("A65536").End(xlUp)(2) 
Next 

End Sub 

回答

0

您已經定義WS爲工作,但還沒有通過除第一每張紙上指定的工作表哪,你再循環。

試試這段代碼 - 它循環遍歷每張紙,但忽略某些命名的紙張。

Sub Combine() 

Dim ws As Worksheet 
Dim shtMaster As Worksheet 
Dim rTargetLastCell As Range 
Dim rSourceLastCell As Range 

Set shtMaster = ThisWorkbook.Worksheets("Master Data") 

'Cycle through each worksheet in the workbook. 
'NB: Worksheets exclude chart sheets and macro sheets. 
For Each ws In ThisWorkbook.Worksheets 
    Select Case ws.Name 
     Case "Invoicing", "Master Data" 
      'Do Nothing 
     Case Else 
      'Find the last cell containing data in the two sheets. 
      Set rTargetLastCell = LastCell(ThisWorkbook.Worksheets("Master Data")) 
      Set rSourceLastCell = LastCell(ws) 

      'Copy and paste the relevant data. 
      With ws 
       .Range(.Cells(2, 1), rSourceLastCell).Copy _ 
        Destination:=shtMaster.Cells(rTargetLastCell.Row + 1, 1) 
      End With 
    End Select 
Next ws 

End Sub 

Public Function LastCell(wrkSht As Worksheet) As Range 

    Dim lLastCol As Long, lLastRow As Long 

    On Error Resume Next 

    With wrkSht 
     lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column 
     lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row 

     If lLastCol = 0 Then lLastCol = 1 
     If lLastRow = 0 Then lLastRow = 1 

     Set LastCell = .Cells(lLastRow, lLastCol) 
    End With 
    On Error GoTo 0 

End Function