如何复制和粘贴两列Excel工作簿之间的数据从一列到另一列…而不覆盖目标列的内容..?

如何将数据从一列复制并粘贴到两张Excel工作簿之间…而不覆盖目标列内容?

我正在使用下面的代码来复制和粘贴,但每次我运行它是覆盖已有的内容。 我想从列的下一行粘贴。

Sub DirectCopySample() Application.ScreenUpdating = False Sheets("Updating Sheet").Range("A:A").Copy Destination:=Sheets("Sheet1").Range("G:G") Sheets("Updating Sheet").Range("B:B").Copy Destination:=Sheets("Sheet1").Range("F:F") Sheets("Updating Sheet").Range("C:C").Copy Destination:=Sheets("Sheet1").Range("B:B") Application.ScreenUpdating = True End Sub 

@“Eh'Bacon老师在他或她的评论中概述了正确的过程。

问题的症结在于find你正在复制和粘贴的范围的大小。 我目前最喜欢的方法是下面的代码片段:

 copyLastrow = Sheets("Updating Sheet").Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row 

这将在工作表中find最后一个非空行。 所以如果由于某种原因,列A有100行,B有200行,而C有300行,它将返回300作为最后一行。

在事物的粘贴面上,您可以使用相同的方法,并将其添加1,以便粘贴到第一个空行,但是如果列的行数不同,则最终会在较短的列中显示许多空行数据粘贴在底部。

一个解决这个问题的是以下代码:

  pasteLastrowG = Sheets("Sheet1").Range("G" & Rows.Count).End(xlUp).Row + 1 

这将从G列底部开始,直到它碰到一行数据,然后加1,以便粘贴到列的第一个空白行。 然后你可以创buildH和I列的variables来做同样的事情。

把它放在一起你的代码最终会看起来像这样:

 copyLastrow = Sheets("Updating Sheet").Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row pasteLastrowG = Sheets("Sheet1").Range("G" & Rows.Count).End(xlUp).Row + 1 'pasteLastrowH ... 'pasteLastrowI ... Sheets("Updating Sheet").Range("A2:A" & copyLastrow).Copy Destination:=Sheets("Sheet1").Range("G" & pasteLastrowG) 'Copy and paste B code here 'Copy and paste C code here 

不要复制整个列。 复制特定的1单元范围的X行(其中X是您的数据),并根据当前的数据大小定义所有variables。 例如,如果要将sheet1中的列A复制到sheet2中的列B的末尾。

 Sub CopyColumn() Dim wsCopy As Worksheet Set wsCopy = Sheets("<Sheet Name>") Dim wsPaste As Worksheet Set wsPaste = sheets("<Sheet Name>") '/ Much better to make your worksheets variables and then reference those Dim lngFirstRow As Long Dim lngFinalRow As Long Dim lngCopyColumn As Long Dim lngPasteColumn As Long Dim rngCopy As Range Dim rngPasteCell As Range lngCopyColumn = 1 '/ ("A" Column) lngDestinationColumn = 2 '/ ("B" Column) wsCopy.Activate lngFirstRow = 1 lngFinalRow = Cells(1048576, lngCopyColumn).End(xlUp).Row '/ Starts at the bottom of the sheet, stops at the first cell with data in it, returns that cell's row Set rngCopy = Range(Cells(lngFirstRow, lngCopyColumn), Cells(lngFinalRow, lngCopyColumn)) '/ Defines the range between those 2 cells rngCopy.copy wsPaste.Activate lngFinalRow = Cells(1048576, lngPasteColumn).End(xlUp).Row Set rngpaste = Cells(lngFinalRow + 1, lngPasteColumn) '/ Pastes to the row 1 cell below the last filed cell in Column B rngpaste.Paste End Sub