使用vba

时间:2017-08-06 13:34:42

标签: excel-vba vba excel

我对VBA编码相对较新...我当前的问题是如何使用VBA在表中创建列名...感谢stackoverflow guru的建议我已经创建了sub来这样做...它可以工作但是它添加了比列出的数组更多的列...不知道为什么会发生这种情况......任何建议都会非常感激......两个潜艇的代码如下......

Sub colNames()

 Dim lst As ListObject
 Dim currentSht As Worksheet
 Dim h As Long, hdrs As Variant

    hdrs = Array("Employee Name", "Hourly Rate", "Status", "Benefits?", "Street Number", "City", "Prov", "PC", "SIN #")
    Call CreateTable

    Set currentSht = ActiveWorkbook.Sheets("EmpTBL")

    Set lst = ActiveSheet.ListObjects("Table1")

    With lst 'ActiveSheet.ListObjects("Table1")
        For h = 0 To 8
            .ListColumns.Add
            .ListColumns(.ListColumns.Count).Name = hdrs(h)
        Next h
    End With

End Sub

Sub CreateTable()
    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes).Name = _
        "Table1"
        'No go in 2003
    ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight2"
End Sub

这些返回一个表但是从B1开始的前三列是1,2,3列,然后数组名称?????

1 个答案:

答案 0 :(得分:0)

尝试下面的代码(代码中的解释作为注释):

Option Explicit

Sub colNames()

Dim lst As ListObject
Dim currentSht As Worksheet
Dim h As Long, hdrs As Variant

    hdrs = Array("Employee Name", "Hourly Rate", "Status", "Benefits?", "Street Number", "City", "Prov", "PC", "SIN #")

    ' first Set the worksheet object
    Set currentSht = ActiveWorkbook.Sheets("EmpTBL")

    ' now set the ListObject (table)
    Set lst = currentSht.ListObjects.Add(xlSrcRange, currentSht.Range("B1:B16"), , xlYes)
    With lst ' modify the Table object properties
        .Name = "Table1"
        .TableStyle = "TableStyleLight2"

        ' replace the first column name with the first element in the array
        .ListColumns(1).Name = hdrs(0)

        ' loop throughout the other elements in the array (from 2nd)
        For h = 1 To UBound(hdrs)
           .ListColumns.Add
           .ListColumns(.ListColumns.Count).Name = hdrs(h)
        Next h
    End With

End Sub