简体   繁体   English

复制和粘贴多个单元格而不会覆盖现有单元格EXCEL VBA

[英]Copy and paste multiple cells without overwriting existing cells EXCEL VBA

Looking for a bit of guidance. 寻找一些指导。

I am trying to copy all cells from 4 worksheets into a master sheet. 我试图将所有单元格从4个工作表复制到一个主表。

I can copy one sheet of data to the master sheet but when i copy a second sheet it will overwrite the information previously copied to the master sheet. 我可以将一张数据复制到母版,但是当我复制第二张纸时,它将覆盖先前复制到母版的信息。

This is the code that i am currently using to copy the data. 这是我当前用于复制数据的代码。

Sub Create_Master ()

    Dim sourceColumn As Range, targetColumn As Range

    Set sourceColumn = Worksheets("Sheet1").Columns("A:P")
    Set targetColumn = Worksheets("Master Sheet").Columns("A:P")

    sourceColumn.Copy Destination:=targetColumn

End sub

Any Thoughts? 有什么想法吗?

Cheers Adam 干杯亚当

Something like this might work for you ... 这样的事情可能适合您...

Sub Create_Master ()

 Dim sourceSheet As Worksheet Dim sourceRange As Range Dim sourceRows As Integer Set sourceSheet = Worksheets("Sheet1") sourceRows = WorksheetFunction.CountA(sourceSheet.Range("A:A")) Set sourceRange = sourceSheet.Range("A1:P" & sourceRows) Dim targetSheet As Worksheet Dim targetRange As Range Dim targetRows As Integer Set targetSheet = Worksheets("Master Sheet") targetRows = WorksheetFunction.CountA(targetSheet.Range("A:A")) Set targetRange = targetSheet.Range("A" & targetRows + 1 & ":P" & targetRows + 1 + sourceRows) sourceRange.Copy Destination:=targetRange 

End Sub

It's using the worksheet function "CountA" to work out how may rows are in use, assuming that column A cells are always populated and that you don't have any data in that column below the stuff you want to copy. 它使用工作表函数“ CountA”来计算行的使用情况,假设始终填充A列单元格,并且该列中没有要复制的内容的任何数据。 If you have column headings on the source sheet and the master then they'll get duplicated. 如果源工作表和母版上都有列标题,则它们将重复。 So you might want to make the sourceRange start at A2. 因此,您可能要使sourceRange从A2开始。

HTH. HTH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM