向散点图添加额外系列

Adding extra series to scattergraph

我正在尝试创建一个将系列添加到散点图的代码。代码运行但添加了大约 100 个未指定的额外数据系列。我的 vba 技能很基础。

Dim DownSweep As Chart
Dim xrng As Range
Dim yrng As Range
Dim title As Range
Dim dsvt As Worksheet
Dim dst As Worksheet
Dim i As Integer

t = 1

CLEAN:
    If t < ActiveWorkbook.Charts.Count + 1 Then
    If ActiveWorkbook.Charts(t).Name = "DownSweep Graph" Then
    Application.DisplayAlerts = False
    ActiveWorkbook.Charts("DownSweep Graph").Delete
    Application.DisplayAlerts = True
    t = t + 1
    GoTo CLEAN
    End If
    End If

    Set dst = Worksheets("Template 2 - Down Sweep")
    Set dsvt = Worksheets("DownSweep ViscosityTemperature")

Set xrng = dsvt.Range(dsvt.Range("C2"), dsvt.Range("C2").End(xlDown))
Set yrng = dsvt.Range(dsvt.Range("F2"), dsvt.Range("F2").End(xlDown))
Set title = dsvt.Range("F1")

dsvt.Range("E1").Select

    Set DownSweep = Charts.Add
    DownSweep.Name = "DownSweep Graph"

    With DownSweep
            .ChartType = xlXYScatter
            .SeriesCollection.NewSeries
            .SeriesCollection(1).XValues = xrng
            .SeriesCollection(1).Values = yrng
            .SeriesCollection(1).Name = title
    End With

title = title.Offset(0, 1)

For i = 2 To 99
        With DownSweep.SeriesCollection.NewSeries()
            .XValues = xrng.Offset(0, i - 1).Value
            .Values = yrng.Value
            .Name = title
        End With
        title = title.Offset(0, i)
    Next i

End Sub

如何防止这种情况发生?

如有任何帮助,我们将不胜感激。

那是因为您在添加图表之前在源数据中选择了一个单元格。因此它会自动将该数据设置为源并创建系列集合。

因此,要么确保活动单元格不在源数据中,要么在添加新系列集合之前使用以下代码删除现有系列集合。

With DownSweep
    Do While .SeriesCollection.Count > 0
        .SeriesCollection(1).Delete
    Loop
End With