VBA add row to table but can't use table name

dsrt16

Board Regular
Joined
Jun 18, 2005
Messages
208
I have a table called MileageChart on a sheet called Template where when a user presses add row, a new row is added. The VBA code works like a charm. However, there is one problem.

At the start of every year, the template sheet is duplicated and then user is prompted to rename it the name of the new year.

So when the sheet gets duplicated, the table on the new sheet is now called MileageChart1, so then the new row button won't work because there is no ListObject MileageChart on that sheet.

This is the only table on the worksheet; the rest is ranges. So is there a way to get the VBA code to just add a row to the table on the sheet from where the user presses the button regardless of the name of the table?

The code I am currently using which is name specific:

Code:
Sub AddRow1()

Dim ws As Worksheet
Set ws = ActiveSheet
Dim tbl As ListObject
Set tbl = ws.ListObjects("MileageChart")


tbl.ListRows.Add (1)

tbl.ListRows(2).Range.Copy
tbl.ListRows(1).Range.PasteSpecial xlPasteFormats

tbl.ListRows(1).Range.Select

Call Formulalock

End Sub
 

Excel Facts

Back into an answer in Excel
Use Data, What-If Analysis, Goal Seek to find the correct input cell value to reach a desired result
dsrt16,

Try changing this line...

Code:
Set tbl = ws.ListObjects("MileageChart")

to...

Code:
Set tbl = ws.ListObjects(1)

Cheers,

tonyyy
 
Upvote 0
I was about ready to answer this when Tony had the answer.

Just curious what your overall object is.
Not sure why you think you need to add rows like this.

And what does this script do:

Call Formulalock
 
Upvote 0

Forum statistics

Threads
1,214,896
Messages
6,122,132
Members
449,066
Latest member
Andyg666

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top