I have been trying to modify my VBA code in order to add an extra row only on the specified table and not on the whole sheet. I have tried a few different options, checked with ChatGPT as well but nada.
Some key points:
I want to have a flexible code so i can use it in different templates; meaning:
- the table name will differ in each template (however, there will be a common star word: Table)
- the table column numbers are unlikely to change, but in case it ever does, i want that to be flexible too. Hence, I wanted to use a generic "tbl" variable as there will always be one table in all the sheets i will use this code on.
Here below is my code:
Sub AddRowToTable()
Dim tbl As ListObject 'Needed to reference a table '
Dim selectedCell As Range
On Error Resume Next
'Temporarily ignore the error that might occur during exec.'
'e.g., user clicks Cancel / ESC'
Set selectedCell = Application.InputBox("Select a cell in the table below:", Type:=8)
'Prompt the user to select a cell'
On Error GoTo 0
Set tbl = selectedCell.Worksheet.ListObjects(1) 'Assumes that there is only one table in the active sheet'
If Not tbl Is Nothing And Not selectedCell Is Nothing Then 'Check if the selection is within the table'
If Not Intersect(selectedCell, tbl.DataBodyRange) Is Nothing Then
selectedCell.Offset(1, 0).EntireRow.Insert
'Insert a row below the selected cell within the table'
Else
MsgBox "Please select a cell within the table below."
End If
Else
MsgBox "No table found in the active sheet. Contact template owner."
End If
End Sub
Please try
OR
Microsoft documentation: