如何在 Excel VBA 中将每第 8 列添加到图表中

问题描述 投票:0回答:1

我不知道如何仅添加从 Z 列开始的每 8 列数据。范围应始终从第 27 行到第 194 行。

这是我目前用于创建图表的代码。我想用其他内容替换手动范围(Z $ 27:Z $ 194,AH $ 27:AH $ 194,...),因为我有很多列。

预先感谢您的帮助!

Sub Graph_VBA()
Cells(713, 1).Select
ActiveSheet.Shapes.AddChart2(227, xlLineMarkersStacked100).Select
ActiveChart.SetSourceData Source:=Range("Z$27:Z$194,AH$27:AH$194,AP$27:AP$194,AX$27:AX$194,BF$27:BN$194,BF$27:BN$194")
ActiveChart.ChartTitle.Text = "Winter"
ActiveChart.ChartArea.Height = 400
ActiveChart.ChartArea.Width = 750
ActiveChart.Parent.Cut
Cells(713, 1).PasteSpecial
End Sub
excel vba graph
1个回答
0
投票

首先,让我们尽量不要使用

Select

Sub Graph_VBA()
    Dim shp AS Shape, cht AS Chart
    Set shp = ActiveSheet.Shapes.AddChart2(227, xlLineMarkersStacked100)
    Set cht = shp.Chart
    cht.SetSourceData Source:=Range("Z$27:Z$194,AH$27:AH$194,AP$27:AP$194,AX$27:AX$194,BF$27:BN$194,BF$27:BN$194")
    cht.ChartTitle.Text = "Winter"
    cht.ChartArea.Height = 400
    cht.ChartArea.Width = 750
    shp.Top = ActiveSheet.Cells(713, 1).Top
    shp.Left = ActiveSheet.Cells(713, 1).Left
End Sub

接下来,让我们使用

SeriesCollection
对象(更具体地说,
SeriesCollection.Add
方法
)通过循环逐一添加列,而不是一次性添加所有列:

Sub Graph_VBA()
    Dim shp AS Shape, cht AS Chart, i as Long, col AS Long, rng AS Range
    Set shp = ActiveSheet.Shapes.AddChart2(227, xlLineMarkersStacked100)
    Set cht = shp.Chart
    
    For i = 1 to 6 'Add 6 columns
        col = 26 + ((i-1)*8) 'Every 8th column, starting at Z (26)
        Set rng = ActiveSheet.Range(ActiveSheet.Cells(27, col), _
            ActiveSheet.Cells(194, col)) 'Rows 27 to 194
        'Add "Rng", as a Data Column, with a Header in the first row, and Replace existing data
        cht.SeriesCollection.Add rng, xlColumns, True, True
    Next i
    
    cht.ChartTitle.Text = "Winter"
    cht.ChartArea.Height = 400
    cht.ChartArea.Width = 750
    shp.Top = ActiveSheet.Cells(713, 1).Top
    shp.Left = ActiveSheet.Cells(713, 1).Left
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.