如何解决由.PasteSpecial引起的编译错误?

时间:2019-11-28 17:14:17

标签: vba compilation copy paste

我正在努力解决以下问题,但无法使代码正常工作。

    Sub Copy_Paste_Below_Last_Cell()
'Find the last used row in both sheets and copy and paste data below existing data.

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 = ThisWorkbook.Worksheets("Data")
  Set wsDest = Workbooks("Data.xlsx").Worksheets("DB")

  '1. Find last used row in the copy range based on data in column A
  lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").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, "A").End(xlUp).Offset(1).Row

  '3. Copy & Paste Data
  wsCopy.Range("A2:H" & lCopyLastRow).Copy _
  wsDest.Range("A" & lDestLastRow).PasteSpecial xlPasteValues



End Sub

问题出现在最后一行。在不添加PasteSpecial xlPasteValues的情况下,脚本可以完美运行。但是,由于它是从带有表单的线的大工作表中拉出的,因此目标工作表中充满了带有公式的空行。当我用新数据重新运行脚本时,它会寻找最新的空行,但是由于公式原因,这比实际数据低了几行。

可视化:

Data Row 1
Data Row2
Formula row
Formula row
Empty row

运行2

Data Row 1
Data Row2
Formula row
Formula row
Data Row 3
Formula Row

1 个答案:

答案 0 :(得分:1)

我怀疑是因为Copy和PasteSpecial方法在同一行上。请尝试以下操作,它应该可以工作。

 Sub Copy_Paste_Below_Last_Cell()
'Find the last used row in both sheets and copy and paste data below existing data.

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 = ThisWorkbook.Worksheets("Data")
  Set wsDest = Workbooks("Data.xlsx").Worksheets("DB")

  '1. Find last used row in the copy range based on data in column A
  lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").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, "A").End(xlUp).Offset(1).Row

  '3. Copy & Paste Data
  wsCopy.Range("A2:H" & lCopyLastRow).Copy
  wsDest.Range("A" & lDestLastRow).PasteSpecial xlPasteValues
  Application.CutCopyMode = False

End Sub

添加了Application.CutCopyMode = False,以便在执行复制粘贴后清除剪贴板。

相关问题