2017-08-06 176 views
1

我对VBA编码相对较新......我当前的问题是如何在使用VBA的表格中创建列名称......感谢来自stackoverflow guru的建议,这样做...它的工作原理,但它增加了比列阵更多的列...不知道为什么会发生这种情况...任何建议将非常感谢...两个潜艇的代码如下...使用vba在表格中创建列名称

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,然后数组名称?????

+0

子2Sub CREATETABLE() ActiveSheet.ListObjects.Add(xlSrcRange,范围( “$ B $ 1:$ d $ 16”), ,xlYes),请将.Name = _ “表1” “没有在2003年 ActiveSheet.ListObjects去( “表1”)TABLESTYLE = “TableStyleLight2” 结束小组 –

+1

你应该学会如何调试VBA程序 - 阅读:HTTP ://www.cpearson.com/Excel/DebuggingVBA.aspx – Graham

+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 
+0

...非常感谢你。 ..works完美... –

+0

@JeffHolmes欢迎您,现在将您的角色标记为“答复”,点击答案左侧的灰色复选标记,它会变成绿色 –

相关问题