2017-08-16 26 views
0

我已经创建了一个宏,它会自动获取一系列单元格并将它们格式化为表格。如果表名存在,更改表名称(VBA)

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

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

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

这里是我的代码:

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 

回答

4

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

enter image description here


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