Excel VBA: 向列表对象添加列而不向工作表添加列

Excel VBA: Adding columns to ListObject wihtout adding Columns to Worksheet

我是 运行 VBA Excel 中的代码,用于在单击按钮后构建 table (ListObject)。 将通过对 header 名称使用 collection 来动态添加列。 在构建 table 之前,删除现有的 table 以避免错误。

使用 ListColums.Add 的问题在于它会将列添加到整个 sheet 并将现有列推到右侧。因此,每次单击该按钮时,sheet 的列数都会越来越多。这不是很干净。该按钮将被非常频繁地按下,我想避免达到 Excel Worksheets 的极限。我的构建函数的工作原理如下:

Function buildTable(wsName As String, tblName As String, clmns As Collection, Optional tableRange As String)

    ' * If Range is not specified choose "$A"
    If IsMissing(tableRange) Then
        position = "$A"
    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,但这只会清空已经为空的列,而不会删除它们...

有没有办法做到这一点,而不是每次单击按钮时 sheet 末尾的列越来越多?

好的,Rory 说的有道理。

没有添加任何列,但视图空间不断增长(滚动条缩小)。

所以我所要做的就是 ThisWorkbook.Worksheets(wsName).UsedRange.SpecialCells (xlCellTypeLastCell) 我找到了 here

谢谢!