簡體   English   中英

VBA使用lastrow范圍將數據從一個工作簿復制到另一個工作簿

[英]VBA Copying data from one workbook to another using lastrow ranges

在工作簿上帶有數據透視表的工作表上有一個按鈕,名為“ Warranty Template.xlsm”。 我希望此按鈕復制從A5開始的第一列數據,並將該列粘貼到另一個名為“ QA Matrix Template.xlsm”的工作簿中。 我希望復制的數據在列的最后空白行結束,並且我希望粘貼的范圍也要粘貼到從D12開始的第一行空白處。

Sub InsertData()


Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim lCopyLastRow As Long
Dim lDestLastRow As Long

  'Set variables for copy and destination sheets
  Set wsCopy = Workbooks("Warranty Template.xlsm").Worksheets("PivotTable")
  Set wsDest = Workbooks("QA Matrix Template.xlsm").Worksheets("Plant Sheet")

  '1. Find last used row in the copy range based on data in column A
  lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A5").End(xlUp).Row

  '2. Find first blank row in the destination range based on data in column A
  'Offset property moves down 1 row
  lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "D12").End(xlUp).Offset(1).Row

  '3. Copy & Paste Data
  wsCopy.Range("A5" & lCopyLastRow).Copy _
    wsDest.Range("D12" & lDestLastRow)

End Sub

我收到下標錯誤:“ 1004”,我不確定為什么。 它與我的lCopyLastRowlDestLastRow變量有關。 如果我設置靜態范圍,但是我需要這些范圍是動態的,則代碼可以工作。

Sub InsertData()

Dim wsCopy As Worksheet, wsDest As Worksheet
Dim lCopyLastRow As Long, lDestLastRow As Long

'Set variables for copy and destination sheets
Set wsCopy = Workbooks("Warranty Template.xlsm").Worksheets("PivotTable")
Set wsDest = Workbooks("QA Matrix Template.xlsm").Worksheets("Plant Sheet")

'1. Find last used row in the copy range based on data in column A
lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, 1).End(xlUp).Row

'2. Find first blank row in the destination range based on data in column A
'Offset property moves down 1 row
lDestLastRow = wsDest.Cells(wsDest.Rows.Count, 4).End(xlUp).Offset(1,0).Row

'3. Copy & Paste Data
wsCopy.Range("A5:A" & lCopyLastRow).Copy _
wsDest.Range("D" & lDestLastRow)

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM