如何将范围粘贴到另一个带有过滤器的工作表上

时间:2016-09-15 14:31:51

标签: excel macros runtime-error paste worksheet

这似乎是一项简单的任务,但我一直遇到各种错误。我需要过滤工作表B,然后复制一列数据。然后,我需要过滤工作表A,然后将复制的数据粘贴到列中。

Worksheets("SheetB").Select

lastRowOne = Range("B" & Rows.Count).End(xlUp).Row
Range("DL2:DL" & lastRowOne).AutoFilter Field:=116, Criteria1:="<>Apples"



 lastRowTwo = Range("B" & Rows.Count).End(xlUp).Row
 Range("DG2:DG" & lastRowTwo).AutoFilter Field:=111, Criteria1:=Target

'Target is already defined earlier in the Macro and functions fine


 lastRowThree = Range("B" & Rows.Count).End(xlUp).Row
 Range("DX2:DX" & lastRowThree).Copy


Worksheets("SheetA").Activate


lastRowFour = Range("B" & Rows.Count).End(xlUp).Row
Range("A2:A" & lastRowFour).AutoFilter Field:=1, Criteria1:=Target


lastRowFive = Range("B" & Rows.Count).End(xlUp).Row

Range("Z2:Z" & lastRowFive).SpecialCells(xlCellTypeVisible).Select

 Selection.PasteSpecial Paste:=xlPasteRange, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

代替最后一行,我也尝试过:

ActiveSheet.Paste

第一个返回&#34;运行时错误&#39; 1004&#39;: 范围类的PasteSpecial方法失败

ActiveSheet.Paste返回&#34;运行时错误&#39; 1004&#39;: Worksheet类的粘贴方法失败

虽然这段代码并不是最干净的,但除了&#34;粘贴&#34;进入&#39; sheetA&#39;在列Z中。如果可以将其包含在修复程序中,我还需要将数据粘贴到AA中。

谢谢!

1 个答案:

答案 0 :(得分:0)

这是(我希望)相同的宏,但没有.Select / .Activate,还有一点调整。例如,您不需要多个“lastRow”变量。由于你真的只是重置它,你可以使用它。

Sub tester()
' First create, then SET, worksheet variables to hold the sheets. We use these when
' referring to ranges, cells, etc.
Dim aWS As Worksheet, bWS As Worksheet
Set aWS = Worksheets("SheetA")
Set bWS = Worksheets("SheetB")

Dim lastRow As Long 'AFAICT, you only need this one Last Row variable. Just update it each time.
Dim copyRng As Range

With wsB ' working with SheetA
    lastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
    .Range("DL2:DL" & lrOne).AutoFilter Field:=116, Criteria1:="<>Apples"

    lastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
    .Range("DG2:DG" & lastRow).AutoFilter Field:=111, Criteria1:=Target

    lastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
    ' We now SET the range we want to copy. We can avoid copy/paste by setting two ranges equal
    ' to eachother. For now, let's store the COPY RANGE in a Range variable
    Set copyRng = .Range("DX2:DX" & lastRow).SpecialCells(xlCellTypeVisible)

End With 'bWS

Dim pasteRng As Range
With aWS
    lastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
    .Range("A2:A" & lastRow).AutoFilter Field:=1, Criteria1:=Target

    lastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
    Set pasteRng = .Range("Z2:Z" & lastRow).SpecialCells(xlCellTypeVisible)
End With 'aWS

pasteRng.Value = copyRng.Value

End Sub

我唯一犹豫的是对SpecialCells的粘贴。 AFAIK,如果粘贴范围与复制范围不同,则可能会出现一些错误。无论如何,试试上面的内容,让我知道会发生什么。

使用多个工作表时,尤其是需要注意的一件重要事情是,您应该明确表示要获取Range()Cells()的工作表, Rows()Columns(),等等。否则,它将获得该信息。来自ActiveSheet,无论可能是什么。