Excel VBA,将不均匀数据区域复制并粘贴到其他工作表

yc0p9oo0  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(145)

当我使用此代码将数据追加到另一个工作表时,当范围不均匀时(即一列的数据多于另一列),一些数据会被替换。最后一行只基于一列,但我需要它基于2列。我该如何做到这一点?谢谢!

Sub CopyData()

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

  Set wsCopy = Sheets("CopyFrom")
  Set wsDest = Sheets("PasteHere")

  lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "B").End(xlUp).Offset(1).Row

  wsCopy.Range("C3:F20").Copy
  wsDest.Range("B" & lDestLastRow).PasteSpecial
  
  'Copy & Paste Date
  wsCopy.Range("B1").Copy
  wsDest.Range("A" & lDestLastRow).PasteSpecial

End Sub
ccrfmcuu

ccrfmcuu1#

添加另一个变量来存储另一列的长度(我称之为tempLrow),然后选择最大值。在下面的答案中,我使用列A作为示例,但您可以替换为任何其他列-或多次执行相同操作,以获得更多不同列的最大长度。

Sub CopyData()

Dim wsCopy As Worksheet, wsDest As Worksheet
Dim lCopyLastRow As Long, lDestLastRow As Long, lDestLastColumn As Long, tempLRow as Long

Set wsCopy = Sheets("CopyFrom"): Set wsDest = Sheets("PasteHere")

'Last row of column B:
lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "B").End(xlUp).Offset(1).Row
'Last row of column A:
tempLRow = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Offset(1).Row
' if column A is longer than column B, update lDestLastRow to suit:
If tempLRow > LDestLastRow Then LDestLastRow = tempLRow

wsCopy.Range("C3:F20").Copy Destination:=wsDest.Range("B" & lDestLastRow)
  
'Copy & Paste Date
wsCopy.Range("B1").Copy Destination:=wsDest.Range("A" & lDestLastRow)

End Sub

相关问题