Home » excel » excel – Insert rows in a table based on number of rows from another worksheet

excel – Insert rows in a table based on number of rows from another worksheet

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am trying to insert a specific number of rows into a table based on criteria of number of rows from another worksheet. What I want to do is insert the rows below the top line in the table. I am trying all sorts of code but to no avail, this is what I have and some code at the bottom that I have tried.

'Counts number of rows 
Int_rows = Range("m7:y7").End(xlDown).Row - 6
Windows("Sheet2").Activate
ActiveSheet.ListObjects("Table").Resize (Int_rows), (0)
'ActiveSheet.ListObjects("APR_Table").ListRows.Add (2)
'Range("Table").Resize(Int_Rows).EntireRow.Insert
How to&Answers:

Please consider using the following code:

Sub AddRows()
    Dim Int_rows As Integer
    Int_rows = Sheets("Sheet1").Range("m7:y7").End(xlDown).Row - 6

    Sheets("Sheet2").Rows("2:" & (Int_rows + 1)).Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub

Regards,

Answer:

AFAIK, you can only insert ListRows one at a time through VBA.

The following will work.

Int_rows = Range("m7:y7").End(xlDown).Row - 6

Dim LO as ListObject
Set LO = Worksheets("Sheet2").ListObjects("Table")

For x = 1 to Int_rows
     LO.ListRows.Add , AlwaysInsert:=True
     x = x +1
Next