简体   繁体   中英

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.

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. 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.

HTH.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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