简体   繁体   中英

Create Table in Excel Worksheet using VBA

I have this code below that will auto select a range. Does anyone know how I can add code to create a table to the selected range?

Thanks!

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

Use the following Excel VBA code snippet to add the Table object corresponding to selected Range :

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

You can also apply optional styling to the added Table object like shown below:

objTable.TableStyle = "TableStyleMedium2"

More details available at MSDN: https://msdn.microsoft.com/en-us/library/office/ff823155.aspx

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM