TheMacroNoob
Board Regular
- Joined
- Aug 5, 2022
- Messages
- 52
- Office Version
- 365
- Platform
- Windows
Hello excel experts,
I have a VBA code via the magic of ChatGPT:
There is one problem. The last directive to rename the tables doesn't really work as intended. For example, one of the tables on the 'Template' sheet is "Invoices_Paid". I would expect the duplicated sheet, correctly named "Berry", would have the new table name "Invoices_Paid_Berry", but instead, it is named "Invoices_Paid217_Berry". Numbers are added when you duplicate a table, so I'm wondering how to get around this. Is there a way to store the original table names from "Template" sheet, and then rename based on those values? Or something even easier?
I appreciate any help you can offer.
I have a VBA code via the magic of ChatGPT:
VBA Code:
Sub DuplicateTemplateSheet()
Dim templateSheet As Worksheet
Dim newSheet As Worksheet
Dim sheetList As Worksheet
Dim sheetName As String
Dim lastRow As Long
Dim i As Long
Dim tbl As ListObject
' Set a reference to the Template sheet
Set templateSheet = ThisWorkbook.Sheets("Template")
' Set a reference to the SheetList sheet
Set sheetList = ThisWorkbook.Sheets("SheetList")
' Find the last row of the SheetList sheet
lastRow = sheetList.Cells(sheetList.Rows.Count, "B").End(xlUp).Row
' Loop through the list of sheet names in column B of the SheetList sheet
For i = 2 To lastRow
sheetName = sheetList.Cells(i, "B").Value
' Duplicate the Template sheet and rename the copy with the current sheet name
templateSheet.Copy after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
Set newSheet = ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
newSheet.Name = sheetName
' Loop through all of the tables on the new sheet
For Each tbl In newSheet.ListObjects
' Rename the current table to include the sheet name
tbl.Name = tbl.Name & "_" & sheetName
Next tbl
Next i
End Sub
There is one problem. The last directive to rename the tables doesn't really work as intended. For example, one of the tables on the 'Template' sheet is "Invoices_Paid". I would expect the duplicated sheet, correctly named "Berry", would have the new table name "Invoices_Paid_Berry", but instead, it is named "Invoices_Paid217_Berry". Numbers are added when you duplicate a table, so I'm wondering how to get around this. Is there a way to store the original table names from "Template" sheet, and then rename based on those values? Or something even easier?
I appreciate any help you can offer.