如何从Excel VBA中的另一个工作簿复制单元格范围直到最后一行

时间:2019-01-14 22:44:01

标签: excel vba

我正在尝试复制单元格的范围,直到主工作簿已打开并激活的另一工作簿的最后使用的行。范围需要从C2开始直到M列,然后直到第一行空白。

到目前为止,我所拥有的代码复制了正确的单元格列,但向下延伸到使用过的行上方为空白行。我已经附上了截图。成功将复制的单元格粘贴到主工作簿中。

!(http://tinypic.com/r/29uouwh/9)

Workbooks.Open ("C:\Users\user\Documents\Maintenance Department\General\Equipment Documentation\Holding Furnace\Readings\Data Logs\Flow Sensor Monthly Alarm Log - Inductor.xlsx")
ThisWorkbook.Activate

LastRow = Cells(Rows.Count, "A").End(xlUp).Row

Workbooks("Flow Sensor Monthly Alarm Log - Inductor.xlsx").Worksheets("Sheet1").Range("C2:M2" & LastRow).Copy

ThisWorkbook.Sheets("Data").Range("C" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues

1 个答案:

答案 0 :(得分:0)

尝试使用WorkbookWorksheet对象,而不要使用Activate

Dim WB As Workbook
Dim DestSht As Worksheet
Dim SourceSht As Worksheet

Set DestSht = ThisWorkbook.Worksheets("Data")

Set WB = Workbooks.Open("C:\Users\user\Documents\Maintenance Department\General\Equipment Documentation\Holding Furnace\Readings\Data Logs\Flow Sensor Monthly Alarm Log - Inductor.xlsx")
Set SourceSht = WB.Worksheets("Sheet1")

LastRow = SourceSht.Cells(Rows.Count, "A").End(xlUp).Row

SourceSht.Range("C2:M" & LastRow).Copy
DestSht.Range("C" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues