Excel VBA可在不使用范围的情况下制作多个图形

时间:2020-10-07 00:43:19

标签: excel vba

我想要多个序列图。

我将这段代码显示为三行。

但是,它不起作用,我不能使用Range,因为我的数据源在三行("I1:I30","I51:I80","I101:I131")上稀疏

With ActiveSheet.Shapes.AddChart.Chart
    .HasTitle = True
    .ChartTitle.Text = "My Graph"
    .ChartType = xlLine
    .SetSourceData Range("I1:I30","I51:I80","I101:I131") 'thats the data for three lines I want to show.
    .SeriesCollection(1).Name = "item1" 
    .SeriesCollection(1).XValues = Range("G1:G30") 

我该如何解决?

2 个答案:

答案 0 :(得分:1)

范围设置错误。

Range("I1:I30","I51:I80","I101:I131")

范围应设置如下。

Range("I1:I30, I51:I80, I101:I131")

但是,如果x轴的范围恒定,则创建散点图是合适的。

Sub test()
    Dim sourRange(1 To 3) As Range
    Dim Srs As Series
    Dim Cht As Chart
    Dim i As Integer
    
    Set sourRange(1) = Range("i1:i30")
    Set sourRange(2) = Range("i51:i80")
    Set sourRange(3) = Range("i101:i131")
    
    Set Cht = ActiveSheet.Shapes.AddChart.Chart
    With Cht
        .HasTitle = True
        .ChartTitle.Text = "My Graph"
        .ChartType = xlXYScatterLinesNoMarkers
        For Each Srs In .SeriesCollection
            Srs.Delete
        Next Srs
        For i = 1 To 3
            Set Srs = .SeriesCollection.NewSeries
            With Srs
                .Name = "item" & i
                .Values = sourRange(i)
                .XValues = Range("G1:G30")
            End With
        Next i
    End With
End Sub

答案 1 :(得分:0)

如果数据不在一个连续范围内,则需要分别添加每个系列。手动创建带有工作表不同部分中的数据的图表时,情况相同。您不能选择不连续的范围,然后再插入图表。相反,只需创建一个系列图,然后使用其他单独的命令即可向图表中添加更多系列。