复制过滤的信息

时间:2018-08-31 14:20:30

标签: excel vba

我想将信息从两个不同的工作簿复制到第三个。下面的代码适用于B,但对于A,它仅粘贴第一行信息。

我将A的目标设置为源工作簿的其他选项卡,并且它起作用了。然后,将目标设置为新创建的工作簿,并且也可以工作。

当我再次尝试使用工作簿时,我想在其中输入信息,它只会粘贴第一行。

'open file A
    Set W_Book = Workbooks.Open(Folder_Path & A_Rep)
    Sheets("A").Activate
'filter out information and copy it
    With ActiveSheet
        .AutoFilterMode = False
        .UsedRange.AutoFilter
        .UsedRange.AutoFilter Field:=5, Criteria1:=Start_Date
        .UsedRange.AutoFilter Field:=10, Criteria1:="AAA10"
        .UsedRange.SpecialCells(xlCellTypeVisible).Copy
    End With

'paste on the tracker and close the report
    Windows("Tracker.xlsm").Activate
    Sheets("Sheet A").Range("A1").PasteSpecial
    W_Book.Close False

'open file B
    Set W_Book = Workbooks.Open(Folder_Path & B_Rep)

'filter out information and copy it
    With ActiveSheet
        .AutoFilterMode = False
        .UsedRange.AutoFilter
        .UsedRange.AutoFilter Field:=7, Criteria1:="BBB10" 
        .UsedRange.AutoFilter Field:=24, Criteria1:="Done"
        .UsedRange.SpecialCells(xlCellTypeVisible).Copy
    End With

'paste on the tracker and close the report
    Windows("Tracker.xlsm").Activate
    Sheets("Sheet B").Range("A1").PasteSpecial
    W_Book.Close False

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为您在过滤数据时使用ActiveSheet,但是在打开工作簿B之后,您没有指定要复制的工作表,请尝试下面的代码,它应该会为您提供更好的结果,我指定了第一个工作表复制数据,您可能需要对其进行修改:

Sub foo()
Dim wbTracker As Workbook: Set wbTracker = Workbook("Tracker.xlsm")
'open file A
    Set W_Book = Workbooks.Open(Folder_Path & A_Rep)
'filter out information and copy it
    With W_Book.Sheets("A")
        .AutoFilterMode = False
        .UsedRange.AutoFilter
        .UsedRange.AutoFilter Field:=5, Criteria1:=Start_Date
        .UsedRange.AutoFilter Field:=10, Criteria1:="AAA10"
        .UsedRange.SpecialCells(xlCellTypeVisible).Copy
    End With

'paste on the tracker and close the report
    wbTracker.Sheets("Sheet A").Range("A1").PasteSpecial
    W_Book.Close False

'open file B
    Set W_Book = Workbooks.Open(Folder_Path & B_Rep)

'filter out information and copy it
    With W_Book.Sheets(1)
        .AutoFilterMode = False
        .UsedRange.AutoFilter
        .UsedRange.AutoFilter Field:=7, Criteria1:="BBB10"
        .UsedRange.AutoFilter Field:=24, Criteria1:="Done"
        .UsedRange.SpecialCells(xlCellTypeVisible).Copy
    End With

'paste on the tracker and close the report
    wbTracker.Sheets("Sheet B").Range("A1").PasteSpecial
    W_Book.Close False
End Sub