Search code examples
excelvbarow

Excel-VBA-How to add new row to end of table and unlock new row?


The following works to add a new row to the end of the table and unlock that row. However, I keep getting "Run-Time Error 424: Object Required" despite completing the action.

Don't know why this is happening.

Sub AddRowToTable()

Dim ws As Worksheet
Dim tbl As ListObject
Dim lastRow As ListRow

Set ws = ActiveSheet

Set tbl = ws.ListObjects("Table1")
tbl.ListRows.Add 

Set lastRow = tbl.Range.Rows(tbl.Range.Rows.Count).Row
lastRow.Locked = False


End Sub

Solution

  • Use tbl.ListRows(tbl.ListRows.Count) instead of tbl.Range.Rows(tbl.Range.Rows.Count).Row

    Sub AddRowToTable()
        Dim ws As Worksheet
        Dim tbl As ListObject
        Dim lastRow As ListRow
        
        Set ws = ActiveSheet
        
        Set tbl = ws.ListObjects("Table1")
        tbl.ListRows.Add
        
        Set lastRow = tbl.ListRows(tbl.ListRows.Count)
        lastRow.Range.Locked = False
    End Sub