Home » excel » Is there a faster code for adding a new row to a table – Excel VBA

Is there a faster code for adding a new row to a table – Excel VBA

Posted by: admin April 23, 2020 Leave a comment

Questions:

I add a new row to a table, everytime my code finds a new value to add to it.
The code I use for this Set newRow = ProjectTable.ListRows.Add works fine.
but this makes it run very slow.

Is there a code that accomplishes the same but runs quicker?

Dim ProjectName As String
Dim ResourceType As String
Dim newRow As ListRow
Dim RPLastRow As Long
RPLastRow = RPSheet.Cells(Rows.Count, 1).End(xlUp).Row

For Each cell In RPSheet.Range("A5:A" & RPLastRow)
    If cell = project Then
        Dim cRow As Long
        cRow = cell.Row

        'enter resource type to table
        ResourceType = RPSheet.Range("B" & cRow).Value
        Set newRow = ProjectTable.ListRows.Add
        newRow.Range(1, 1).Value = ResourceType

        'find amount of resources linked to project and add number to table
        ProjectName = project
        newRow.Range(1, 2).Value = Sheet2.NumberOfResources(ProjectName, ResourceType)
    End If
Next cell

EDIT: Added some extra code so its more clear

How to&Answers:

The faster way is to add data to the end of the table and then simply resize it.

Here is an example

ProjectTable.Resize Range("$A$1:$E$" & lRow)

Where lRow is the new last row