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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36874319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:22:53  来源:igfitidea点击:

Create Table in Excel Worksheet using VBA

excelvbaexcel-vbaworksheetlistobject

提问by Jgonzales

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

回答by Alexander Bell

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

使用以下 Excel VBA 代码段添加Table与 selected 对应的对象Range

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

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

您还可以将可选样式应用于添加的Table对象,如下所示:

objTable.TableStyle = "TableStyleMedium2"

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

更多详细信息可在 MSDN:https: //msdn.microsoft.com/en-us/library/office/ff823155.aspx

Hope this will help.

希望这会有所帮助。