Forum Discussion
NotExcellentUser
Sep 03, 2024Copper Contributor
VBA macro to copy & insert new row
I need to build a button-controlled macro to copy a few rows and insert them directly beneath the copied rows. The complicated part is that this needs to be able to repeat itself and move the selecti...
Rodrigo_
Sep 04, 2024Iron Contributor
Hello NotExcellentUser
Sub NewRows()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim lastRow1 As Long, lastRow2 As Long
Dim rng1 As Range, rng2 As Range
' Define your sheets
Set ws1 = ThisWorkbook.Sheets("Working Papers")
Set ws2 = ThisWorkbook.Sheets("Backup")
' Find the last row with data in the sheets
lastRow1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
lastRow2 = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row
' Define the ranges to copy
Set rng1 = ws1.Rows(lastRow1 - 23 & ":" & lastRow1)
Set rng2 = ws2.Rows(lastRow2 - 24 & ":" & lastRow2)
' Insert the copied rows below the last row
rng1.Copy
ws1.Rows(lastRow1 + 1).Insert Shift:=xlDown
rng2.Copy
ws2.Rows(lastRow2 + 1).Insert Shift:=xlDown
' Clear any cut/copied selection to avoid issues
Application.CutCopyMode = False
End Sub
This macro was generated by an AI based on your query; however, it has not been tested.
Explanation:
- Sheets: The code assumes that your "Working Papers" and "Backup" sheets are already set up. Adjust the names if your sheets have different names.
- Last Row Calculation: The code calculates the last row with data in both sheets.
- Ranges to Copy: The ranges rng1 and rng2 are defined based on the last row of data and are then copied.
- Insertion: The code inserts the copied rows directly beneath the last row in both sheets.
- Repetition: Each time you run the macro, it will find the new last row and repeat the process.
How to Set Up the Button:
- Go to the Developer tab in Excel.
- Click on Insert and select a Button.
- Draw the button on your "Working Papers" sheet.
- Assign the NewRows macro to the button.
Repetition:
The macro automatically adjusts the copied rows to the most recent set, allowing infinite repetition.