在两个工作簿之间复制的动态范围

时间:2019-03-04 10:32:34

标签: excel vba

我无法在两个工作簿之间进行动态范围复制。我已经创建了以下代码,并且逐步执行该代码时,我看到“运行时错误1004”“对象工作表的方法范围失败”,我的想法是使用新数据为工作簿创建动态范围,因为它一直在变化并且最后一个包含数据的单元格在“ D”列中,然后将其扩展到“ S”列,并将其复制到“主工作簿数据表”中,再次在D列中找到最后使用的单元格,并将其偏移到“ A”列中。如何完成这项任务?

Sub CopyValuesToMaster()

Dim wsCopy As Worksheet
Dim wsDest As Worksheet

Dim RngAC1 As Range
Dim RngAC2 As Range
Dim NewRng As Range
Dim DestLastRow As Long

Set wsCopy = Workbooks("sl0032019.xls").Worksheets("Sheet1")
Set wsDest = Workbooks("Master-Braun.xlsx").Worksheets("Data")

DestLastRow = Cells(Rows.Count, "D").End(xlUp).Offset(1, -3).Row
CopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "D").End(xlUp).Row

Set RngAC1 = wsCopy.Range("A1")
Set RngAC2 = wsCopy.Range(Cells(Rows.Count, "D").End(xlUp).Offset(0, 15).Row)
Set NewRng = Range(RngAC1.Address & ":" & RngAC2.Address)

NewRng.Copy wsDest.Range("A" & DestLastRow)

End Sub

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试一下。

Sub CopyValuesToMaster()

Dim wsCopy As Worksheet
Dim wsDest As Worksheet

Dim RngAC1 As Range
Dim RngAC2 As Range
Dim NewRng As Range
Dim DestLastRow As Long

Set wsCopy = Workbooks("sl0032019.xls").Worksheets("Sheet1")
Set wsDest = Workbooks("Master-Braun.xlsx").Worksheets("Data")

DestLastRow = wsDest.Cells(Rows.Count, "D").End(xlUp).Offset(1, -3).Row
CopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "D").End(xlUp).Row

With wsCopy
   Set RngAC1 = .Range("A1")
   Set RngAC2 = .Range("S" & .Cells(.Rows.Count, "D").End(xlUp).Row)
End With

Range(RngAC1, RngAC2).Copy wsDest.Range("A" & DestLastRow)

End Sub