将图表系列名称设置为 Table 列名称而不是系列 1、2、3,

Set Chart Series Name to Table Column Name instead of Series1,2,3,

在 Excel 2010 中,我有以下代码在来自 table 的数据的单独 sheet 上创建图表 ("BMS Data Chart") ("BMS_Data").除了图表系列名称是系列 1、系列 2 等之外,一切都很好......我如何使用 VBA 将这些系列名称设置为 table 在时间的列 header 名称创作?

Sub createBMSChart()
Dim cht As ChartObject
Dim ws As Worksheet
Dim myCht As ChartObject
Dim objSeries As Series
Dim srs As Series
Dim cWs As Worksheet
Dim tbl As Range

Sheets.add after:=Worksheets("BMS Data")
ActiveSheet.Name = "BMS Data Chart"

Set cWs = ActiveSheet
cWs.Tab.Color = vbGreen

Set ws = Worksheets("BMS Data")
Set tbl = ws.Range("BMS_Data")

Set cht = cWs.ChartObjects.add(Left:=10, Width:=1300, Top:=10, Height:=550)
cht.Chart.SetSourceData Source:=tbl
cht.Name = "BMS Data Chart"
Set myCht = cht

    With myCht.Chart
    .ChartType = xlLine
    .HasTitle = True
    .ChartTitle.Text = "BMS Data Chart"
    .Legend.Position = xlBottom
    .Axes(xlCategory).CategoryType = xlCategoryScale
    .Axes(xlCategory).TickLabelPosition = xlLow
    .Axes(xlCategory).MajorTickMark = xlNone
    .Axes(xlCategory).AxisBetweenCategories = False
    End With


    For Each srs In cWs.ChartObjects("BMS Data Chart").Chart.SeriesCollection
        srs.Format.Line.Weight = 1

    Next

cWs.Activate
End Sub

认为您可以通过引用 table 来做到这一点,并且 header 行将自动用作系列名称。我只更改了下面两行加星标的行(根据需要更改 table 名称):

Sub createBMSChart()

Dim cht As ChartObject
Dim ws As Worksheet
Dim myCht As ChartObject
Dim objSeries As Series
Dim srs As Series
Dim cWs As Worksheet
Dim tbl As ListObject

Sheets.Add after:=Worksheets("BMS Data")
ActiveSheet.Name = "BMS Data Chart"

Set cWs = ActiveSheet
cWs.Tab.Color = vbGreen

Set ws = Worksheets("BMS Data")
Set tbl = ws.ListObjects("Table1")          '********************************************

Set cht = cWs.ChartObjects.Add(Left:=10, Width:=1300, Top:=10, Height:=550)
cht.Chart.SetSourceData Source:=tbl.Range   '********************************************
cht.Name = "BMS Data Chart"
Set myCht = cht

With myCht.Chart
    .ChartType = xlLine
    .HasTitle = True
    .ChartTitle.Text = "BMS Data Chart"
    .Legend.Position = xlBottom
    .Axes(xlCategory).CategoryType = xlCategoryScale
    .Axes(xlCategory).TickLabelPosition = xlLow
    .Axes(xlCategory).MajorTickMark = xlNone
    .Axes(xlCategory).AxisBetweenCategories = False
End With

For Each srs In cWs.ChartObjects("BMS Data Chart").Chart.SeriesCollection
    srs.Format.Line.Weight = 1
Next

cWs.Activate

End Sub