如果表名存在,则更改表名称(VBA)

我已经创build了一个自动获取一系列单元格并将其格式化成表格的macros。

我已经将默认表名称设置为“Table11”,但是因为Table11只能在工作簿中存在一次,所以如果尝试使用多次运行macros,则会遇到错误。

有没有办法来修改我的代码,如“如果table11存在,然后改名为table12”?

我并不在意新的表名称是什么,但是我希望代码能够根据需要经常使用,所以如果table11已经被使用了,就把它命名为table12。 如果table12已被使用,请使用table13等。

这是我的代码:

Sub formatMacro() Application.ScreenUpdating = False ActiveCell.CurrentRegion.Select ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes).Name = "Table11" Range("Table11[#All]").Select ActiveSheet.ListObjects("Table11").TableStyle = "TableStyleLight9" With Selection .HorizontalAlignment = xlCenter .WrapText = False .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With ActiveSheet.ListObjects("Table11").ShowTableStyleColumnStripes = True Selection.Columns.AutoFit Selection.Rows.AutoFit Application.ScreenUpdating = True End Sub 

没有必要为表格命名。 使用With ActiveSheet.ListObjects.Add(...)来处理新添加的表。

在这里输入图像说明


 Sub CreateAndFormatTable() Application.ScreenUpdating = False With ActiveSheet.ListObjects.Add(xlSrcRange, ActiveCell.CurrentRegion, , xlYes) .TableStyle = "TableStyleLight9" With .Range .HorizontalAlignment = xlCenter .WrapText = False .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With .ShowTableStyleColumnStripes = True .Range.Columns.AutoFit .Range.Rows.AutoFit End With Application.ScreenUpdating = True End Sub