使用 VBA 在 Excel 工作表中创建 Table

Create Table in Excel Worksheet using VBA

下面的代码会自动 select 一个范围。 有谁知道如何添加代码以在 selected 范围内创建 table?

谢谢!

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

使用以下 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

希望这会有所帮助。