VBA打开新工作簿并复制到最后一行

时间:2012-11-20 16:00:19

标签: vba excel-vba excel-2007 excel

我正在写一个副本到最后一行代码,它似乎每次都复制相同的行数。

代码是打开一个新工作簿,从新工作簿中获取特定工作表,复制所有可用数据,并将其粘贴到原始工作簿中。我的代码在

之下
Dim wkb As Workbook
Dim wkbFrom As Workbook
Dim wks As Worksheet
Dim path As String, FilePart As String
Dim TheFile
Dim loc As String
Dim Lastrow As Long
Dim lr As Long
Dim lr2 As Long

FilePart = Trim(shPivot.Range("E17").Value)
TheFile = Dir(path & "*" & FilePart & ".xls")
Set wkbFrom = Workbooks.Open(loc & path & TheFile & FilePart)
Set wks = wkbFrom.Sheets(shPivot.Range("E15").Value)
Lastrow = ActiveSheet.UsedRange.Rows.Count
lr = shCurrentWeek.Range("A" & Rows.Count).End(xlUp).Row
lr2 = wks.Range("A" & Rows.Count).End(xlUp).Row
Debug.Print lr
Debug.Print lr2

'Copies range from report generated to share drive and pastes into the current week tab of open order report
wks.Range("A2:N" & lr2).Copy wkb.Sheets("Current Week").Range("A4")

'Closes the workbook in the shared drive
wkbFrom.Close False

即使“新打开的工作簿”只有167.我也经常获得187行数据。数据填写“A”列一直到第50行。帮助?!

1 个答案:

答案 0 :(得分:1)

我自己从一些工作表中获取最后一行数据时遇到了麻烦;这是我现在使用的代码,对我来说似乎最一致。

objExcelWks.Range("A1").Offset(objExcelWks.Rows.Count - 1, 0).End(xlUp).Row

也许这会奏效吗?