将列添加到Excel工作表中的选定表

时间:2018-01-28 20:31:11

标签: excel vba excel-vba

我有一个包含10个表的工作表(名为Table1,Table2等)。我想仅为某些表添加一列(例如,Table1,Table7和Table9)。下面的代码成功地将列添加到工作表中的所有表中。有什么建议吗?

Sub LoopThroughMyTables()
    Dim ws As Worksheet
    Set ws = ActiveSheet
    Dim tbl As ListObject

    For Each tbl In ws.ListObjects
        'add a column to the left of the Average column
        Dim newColNum As Integer
        newColNum = Range("CshwsTbl[Average]").Column
        tbl.ListColumns.Add(newColNum).Name = "NewColumn"
    Next tbl
End Sub

1 个答案:

答案 0 :(得分:0)

试试这个:

Sub LoopThroughMyTables()
    Dim ws As Worksheet
    Set ws = ActiveSheet
    Dim tbl As ListObject

    For Each tbl In ws.ListObjects
        If tbl.Name = "Table1" Or tbl.Name = "Table7" Or tbl.Name = "Table9" Then 
            'add a column to the left of the Average column
            Dim newColNum As Integer
            newColNum = Range("Table1[Average]").Column
            tbl.ListColumns.Add(newColNum).Name = "NewColumn"
        End If
    Next tbl

End Sub

如果您的工作表上有很多表格,这将不是最有效的方法。但它简单易懂。

使用String数组的替代代码:

Sub LoopThroughMyTables()
    Dim ws As Worksheet
    Set ws = ActiveSheet
    Dim tbl As ListObject

    Dim tables(3) As String
    tables(0) = "Table2"
    tables(1) = "Table7"
    tables(2) = "Table9"

    For Each tbl In ws.ListObjects
        If IsInArray(tbl.Name, tables) Then 
            'add a column to the left of the Average column
            Dim newColNum As Integer
            newColNum = Range("Table1[Average]").Column
            tbl.ListColumns.Add(newColNum).Name = "NewColumn"
        End If
    Next tbl

End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

我在这里找到了IsInArray函数:How to find if an array contains a string