简体   繁体   中英

Excel VBA Copy, Paste, Insert variable rows

I am very new to VBA. I'm trying to copy rows with data from 1 workbook and insert it to another. The source has variable # of rows. The target has only 10 available rows followed by Merged cells.

My goal is: Count source rows, subtract 10 from it and the result would be the number of rows to be inserted at the target workbook prior to paste.

Example: 32 source rows (varies) - 10 target rows (fixed) = 22 rows to be inserted in the target WB pushing the merged cells down. If the result is <=10, just paste without inserting.

Thank you!

Something like this:

Sub Test()
    Dim sourceRange As Range, destinationRange As Range
    Dim rowsToInsert As Long

    With ThisWorkbook.Worksheets("Sheet1")
        Set sourceRange = .Range(.Range("A1"), .Cells(.Rows.Count, "A").End(xlUp))
    End With
    Set destinationRange = Workbooks("SomeBook.xlsx").Worksheets("Sheet1").Range("A1")

    rowsToInsert = Application.Max(sourceRange.Rows.Count - 10, 0)

    If rowsToInsert > 0 Then destinationRange.Resize(rowsToInsert, 1).EntireRow.Insert

    sourceRange.EntireRow.Copy Destination:=destinationRange
End Sub

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