从工作簿复制,粘贴最后一行+ 1行

时间:2014-06-06 23:37:58

标签: excel vba excel-vba

我有这个代码,但似乎它不起作用。我想要的是在活动工作簿(带数据)上运行宏:

enter image description here

打开数据库(工作簿):

将数据库从范围A2复制到最后一行,其值为:

enter image description here

将其粘贴到活动工作簿的最后一行,位于最后一行:

enter image description here

Set targetWorkbook = Application.ActiveWorkbook

filter = "All Excel Files (*.csv),*.csv"
caption = "database"
customerFilename = Application.GetOpenFilename(filter, , caption)
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
Set targetSheet = targetWorkbook.Worksheets(1)
Set sourceSheet = customerWorkbook.ActiveSheet

LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
targetSheet.Range(LastRow + 1, "A").Activate = sourceSheet.Range("A1:T" & LastRow).Value

customerWorkbook.Close

2 个答案:

答案 0 :(得分:0)

'Comment out -

'LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).row    
'targetSheet.Range(LastRow + 1, "A").Activate = sourceSheet.Range("A1:T" & LastRow).Value

Dim tr As Range    
Dim sr As Range

Set sr = sourceSheet.UsedRange    
Set tr = targetWorkbook.Worksheets("Sheet1").UsedRange

sr.Copy Destination:=tr.End(xlDown).Offset(1, 0)

答案 1 :(得分:0)

2件事:
1)你应该有源lastrow和目标lastrow
2)你的倒数第二个陈述是错误的。

' -- target is activeworksheet
  Set targetworkbook = Application.ActiveWorkbook
  Set targetsheet = targetworkbook.ActiveSheet
  tgtLastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
' -- source is csv file
  Filter = "All Excel Files (*.csv),*.csv"
  Caption = "database"
  customerFilename = Application.GetOpenFilename(Filter, , Caption)
  Set customerworkbook = Application.Workbooks.Open(customerFilename)
  Set sourcesheet = customerworkbook.ActiveSheet
  srcLastRow = sourcesheet.Cells(Rows.Count, 1).End(xlUp).Row
'-- now copy
  sourcesheet.Range("A1:T" & srcLastRow).Copy targetsheet.Rows(tgtLastRow + 1)
  customerworkbook.Close