2016-04-26 115 views
2

我在下面的代碼中會自動選擇一個範圍。 有誰知道我可以如何添加代碼來創建一個表到選定的範圍?使用VBA在Excel工作表中創建表格

謝謝!

Sub DynamicRange() 
'Best used when first column has value on last row and first row has a value in the last column 

Dim sht As Worksheet 
Dim LastRow As Long 
Dim LastColumn As Long 
Dim StartCell As Range 

Set sht = Worksheets("Sheet1") 
Set StartCell = Range("D9") 

'Find Last Row and Column 
    LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row 
    LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column 

'Select Range 
    sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select 

End Sub 

回答

3

使用下面的Excel VBA代碼片段加入與選擇RangeTable對象:

Dim objTable As ListObject 
Set objTable = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes) 

您還可以將可選擇定型於增加Table的物體,像圖所示:

objTable.TableStyle = "TableStyleMedium2" 

更多詳細信息請訪問MSDN:https://msdn.microsoft.com/en-us/library/office/ff823155.aspx

希望這會有所幫助。