2017-08-16 154 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