vba 在 Excel 中通过宏向表格添加列时设置列标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17343275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:54:23  来源:igfitidea点击:

Setting Column Headers When Adding Columns To a Table Via Macro in Excel

excelvbaexcel-vba

提问by detroitwilly

So I'm working on this macro that automatically adds columns to a table based on other columns in the table. So here's the functionality:

所以我正在研究这个宏,它会根据表中的其他列自动将列添加到表中。所以这是功能:

I have a number of columns in this table headed "CY 2010" - "CY 2020". These years will inevitably change. I then want to add a column to the table for each "CY" column. Furthermore, I'd like the headers of these columns to match the year, but say "Content Volume YEAR"

我在这张表中有许多列,标题为“CY 2010” - “CY 2020”。这些年将不可避免地发生变化。然后我想为每个“CY”列在表中添加一列。此外,我希望这些列的标题与年份匹配,但要说“内容量年份”

currently, I have the following code that adds columns appropriately:

目前,我有以下代码可以适当地添加列:

Sub AddContentValueColumns()
'
' AddContentValueColumn Macro
' Adds yearly vehicle content value columns to Propulsion data table.
'

'
    last = [A1].Value               ' cell contains number of "CY" columns in sheet

'   Debug.Print (last)

    For Count = 1 To last
        Dim oSh As Worksheet
        Set oSh = ActiveSheet
        oSh.ListObjects("PropTable").ListColumns.Add
    Next Count

End Sub

This works to add the columns, but it currently just adds the columns to the end of the table labeled as "CY 2021", etc.

这适用于添加列,但它目前只是将列添加到标记为“CY 2021”等的表的末尾。

So how do I modify that code above to name the columns?

那么如何修改上面的代码来命名列呢?

Thanks.

谢谢。

-Sean

-肖恩

回答by mr.Reband

Here's an example of how to change the column name:

以下是如何更改列名称的示例:

last = [A1].Value               ' cell contains number of "CY" columns in sheet
For Count = 1 To last
    Dim oSh As Worksheet
    Set oSh = ActiveSheet
    Dim oLc As ListColumn
    Set oLc = oSh.ListObjects("PropTable").ListColumns.Add
    oLc.Name = "COLUMN NAME" & last
Next Count