VBA - 图表的多个系列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24757100/
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-12 03:51:29  来源:igfitidea点击:

VBA - Multiple series to a chart

excelvbaexcel-vba

提问by docjay

I'm trying to make add two series to a single XYscatter chart via loop. Currently, my code creates two charts. The X values are constant but the Y values change so I added them to an array to preserve them.

我正在尝试通过循环将两个系列添加到单个 XYscatter 图表中。目前,我的代码创建了两个图表。X 值是恒定的,但 Y 值会发生变化,因此我将它们添加到数组中以保留它们。

Sub test()
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("Sheet1")
    Dim thearray(9) As Double
    Dim chrt As Chart
    Dim n As Integer, i As Integer, q As Integer
    For q = 1 To 2
        For i = 0 To 9
            thearray(i) = WorksheetFunction.RandBetween(1, 20)
        Next
        Set chrt = sh.Shapes.AddChart.Chart
        With chrt
            .ChartType = xlXYScatterLines
            .SeriesCollection.NewSeries
            .SeriesCollection(1).Name = "TEST"
            .SeriesCollection(1).XValues = Range("B2:K2")
            .SeriesCollection(1).Values = thearray
            .SeriesCollection(1).MarkerSize = 4
            For n = .SeriesCollection.Count To 2 Step -1
                .SeriesCollection(n).Delete
            Next n
        End With
    Next
End Sub

I appreciate any help offered.

我感谢提供的任何帮助。

Edit: I tried changing

编辑:我尝试改变

.SeriesCollection(1)

To

.SeriesCollection(q)

But it doesn't work.

但它不起作用。

EDIT2: I figured it out. I took

EDIT2:我想通了。我拿了

 Set chrt = sh.Shapes.AddChart.Chart

Out of the loop and replaced 1 with q in .SeriesCollection

出循环并在.SeriesCollection中用q替换1

回答by docjay

The code that works.

有效的代码。

Sub test()
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("Sheet1")
    Dim thearray(9) As Double
    Dim chrt As Chart
    Dim n As Integer, i As Integer, q As Integer
    Set chrt = sh.Shapes.AddChart.Chart
    For q = 1 To 2
        For i = 0 To 9
            thearray(i) = WorksheetFunction.RandBetween(1, 20)
        Next
        With chrt
            .ChartType = xlXYScatterLines
            .SeriesCollection.NewSeries
            .SeriesCollection(q).Name = "HFF " & q
            .SeriesCollection(q).XValues = Range("B2:K2")
            .SeriesCollection(q).Values = thearray
            .SeriesCollection(q).MarkerSize = 4
            For n = .SeriesCollection.Count To 3 Step -1
                .SeriesCollection(n).Delete
            Next n
        End With
    Next
End Sub