我在Excel中运行VBA代码以在单击按钮后构建表(ListObject)。 将使用标题名称的集合动态添加列。 在构建表之前,将删除现有表以避免错误。
使用ListColums.Add
的问题在于它会将列添加到整个工作表并将现有列推向右侧。因此,每次单击按钮时,工作表将包含越来越多的列。这不是很干净。按钮将非常频繁地按下,我想避免推动Excel工作表的限制。我的构建函数的工作原理如下:
Function buildTable(wsName As String, tblName As String, clmns As Collection, Optional tableRange As String)
' * If Range is not specified choose "$A$1"
If IsMissing(tableRange) Then
position = "$A$1"
End If
' * Build the table based on the passed parameters
ThisWorkbook.Worksheets(wsName).ListObjects.Add(xlSrcRange, ThisWorkbook.Worksheets(wsName).Range(tableRange), , xlYes).Name = tblName
' * Declare and define tblName as ListObject in Worksheet wsName
Dim tbl As ListObject
Set tbl = ThisWorkbook.Worksheets(wsName).ListObjects(tblName)
' * Declare and define the columns of table tblName
Dim clmn As ListColumns
Set clmn = tbl.ListColumns
' * Replace the first column name with the first item in our column Collection clmns
tbl.HeaderRowRange(1, 1).Value = clmns.Item(1)
' * Now loop through the rest of the passed header name collection clmns. Start with 2, because 1 was already set in the last step
X = 2
For X = 2 To clmns.Count
' * Add Item X to the table (String from the passed collection clmns) as column.
clmn.Add.Name = clmns(X)
Next X
End Function
我会这样称呼:
' * Declare and fill my Collection of headers
Dim clHeaders As New Collection
clHeaders.Add "MyFirstColumn"
clHeaders.Add "MySecondColumn"
clHeaders.Add "MyThirdColumn"
' * Call the builTable Function
Call buildTable("Sheet1", "MyTable", clHeaders)
我已经尝试了ThisWorkbook.Worksheets("Sheet1").Columns("AS").EntireColumn.Delete
,但这只会清空已经空的列并且不会删除它们...
有没有办法在每次单击按钮时在工作表的末尾添加越来越多的列?
答案 0 :(得分:0)
好的,罗里有一点意见。
没有添加任何列,但视图空间不断增长(滚动条缩小)。
所以我所要做的只是ThisWorkbook.Worksheets(wsName).UsedRange.SpecialCells (xlCellTypeLastCell)
,我发现here
谢谢!