2016-04-26 101 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

希望这会有所帮助。