Question

I have a macro to copy all the used rows in one Excel sheet (ExcelA) to another (ExcelB):

Sub CopyFromOneXL()
Dim myBook As Workbook, newBook As Workbook

Set myBook = ThisWorkbook
Set lRowMyBook = Range("A1").SpecialCells(xlCellTypeLastCell)
Set newBook = Workbooks.Open("C:\Users\user\Desktop\EXCEL\ExcelB.xlsx")

newBook.Activate

Set lRowNewBook = Sheets("Sheet1").Range("A1").SpecialCells(xlCellTypeLastCell)
lastRowNewBook = lRowNewBook.Row
lastRowMyBook = lRowMyBook.Row
lastRowNewBook = lastRowNewBook + 1

    With newBook
    myBook.Sheets("Sheet1").Rows("1:" & lastRowMyBook).Copy .Sheets("Sheet1").Rows(lastRowNewBook)
    .Close savechanges:=True
    End With
End Sub

ExcelB already uses ten rows (serial numbers from 1-10) and I'm using the above macro to add three more rows of data (which is in ExcelA). Is there any way to add serial numbers to ExcelB for the three newly added rows, starting from 11?

The number of rows in both sheets can vary but ultimately I want to add serial numbers to ExcelB starting from where it had left off.

Was it helpful?

Solution

OP wanted to index incremental entries where, conveniently, the index numbers matched the row numbers for entries copied with code from a different worksheet. Rather than add such an index with a loop in the code for copying the increments it was practical to add a formula (=ROW()) for it into the source sheet that would then copy across automatically with the existing code.

OTHER TIPS

When I added the below code, it worked.

With newBook
myBook.Sheets("Sheet1").Rows("1:" & lastRowMyBook).Copy .Sheets("Sheet1").Rows(lastRowNewBook)
    Set newLRowNewBook = Sheets("Sheet1").Range("A1").SpecialCells(xlCellTypeLastCell)
newLastRowNB = newLRowNewBook.Row
'MsgBox newLastRowNB
For i = lastRowNewBook To newLastRowNB
    Cells(i, 1).Formula = "=Row()"
Next
.Close savechanges:=True
End With

Though the macro takes some time to run if there are 1000s of rows. Just wondering if there is any other way to achieve this without using For loop.

Thanks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top