直接复制过滤数据不起作用

时间:2018-07-05 11:41:29

标签: excel vba excel-vba

我想使用直接复制将数据从一个工作簿复制到另一个工作簿,以避免剪贴板使用。

SourceWS = Workbooks("Src").Worksheets("data src").Range("A1", "J" & lastRow)
DestWS = Workbooks("Dest").Worksheets("Data results").Resize(SourceWS.Rows.Count, SourceWS.Columns.Count)
DestWS.Value = SourceWS.Value

(lastrow在宏中定义较早,效果很好)

运行宏时,在第DestWS = Workbooks("Dest").Worksheets("Data results").Resize(SourceWS.Rows.Count, SourceWS.Columns.Count)行收到一条错误消息,告诉Runtime error '404' Object required,但我不知道我的错误在哪里。

另外,还有一个问题,源数据是过滤后的数据,我只想将它们作为目标工作表上的结果数据,但是我不确定它最后是否会这样做。任何人都可以确认和帮助吗?

2 个答案:

答案 0 :(得分:0)

此代码段将所有可见单元格复制到目标工作表上的相同位置,但保留空单元格用于过滤的行。

Dim shSrc As Worksheet, shTrg As Worksheet
Dim cl As Range     ' aux, loop var
Dim rSrc As Range   ' source range
Dim rTrg As Range   ' target range

Set shSrc = WorkBooks("Source.xlsx").Worksheets("source data sheet")
If shSrc Is Nothing Then Exit Sub
Set shTrg = Workbooks("Target.xlsx").Worksheets("Target data sheet")
If shTrg Is Nothing Then Exit Sub

Set rSrc = shSrc.Range("A10:M50")
For Each cl In rSrc.SpecialCells(xlCellTypeVisible)
    shTrg.Cells(cl.Row, cl.Column).Value = cl.Value
Next cl

答案 1 :(得分:0)

设置对象,调整单元格(而不是工作表)的大小,然后复制过滤的数据,然后将所有公式恢复为其可解析的值。

'assumes filter is already in place
SET SourceWS = Workbooks("Src").Worksheets("data src").Range("A1", "J" & lastRow)
SET DestWS = Workbooks("Dest").Worksheets("Data results")
with SourceWS
    .COPY destination:=DestWS.cells(1)
    DestWS.cells.Resize(.Rows.Count, .Columns.Count) = _
      DestWS.cells.Resize(.Rows.Count, .Columns.Count).Value
end with