Excel VBA 图表未绘制第二个系列

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

我试图在一张图表上绘制两个系列,第一个显示随时间变化的实际值,第二个显示它们正在接近的最大值。第一行显示正常,第二个系列已创建并显示在图例中,但绘图上没有显示任何数据。这是我的简化示例:

Sub SimpleDebug()
    Dim test_sheet As Worksheet
    Set test_sheet = ThisWorkbook.Worksheets("TestData")
    Dim ch As Chart
    test_sheet.ChartObjects.Add Left:=750, Top:=50, Width:=400, Height:=300
    Set ch = test_sheet.ChartObjects(1).Chart
    Dim ser As Series
    Set ser = ch.SeriesCollection.NewSeries
    ser.ChartType = xlLine
    ser.XValues = test_sheet.Range("F2:F278")
    ser.Values = test_sheet.Range("K2:K278")
    ser.name = "Running Total"
    
    Dim max_val As Double
    max_val = 175000
    Set ser = ch.SeriesCollection.NewSeries
    ser.ChartType = xlLine
    Dim min_date As Date
    Dim max_date As Date
    min_date = test_sheet.Range("F2").Value
    Debug.Print "min_date: " & min_date
    max_date = test_sheet.Cells(278, 6).Value
    Debug.Print "max_date: " & max_date
    ser.XValues = Array(min_date, max_date)
    ser.Values = Array(max_val, max_val)
    ser.name = "Maximum"
End Sub

调试打印语句确认我从表格中获取了所需的 min_date 和 max_date 值。结果如下:

我不知道为什么第一个系列绘制得很好而第二个系列根本没有出现。我尝试将第二个系列设置为完全独立的变量,而不是重新使用“ser”,但它没有产生任何影响。

excel vba charts
1个回答
0
投票

不使用最小和最大日期,只需使用与第一个

XValues
相同的
Series
,并为
Values
创建一个相同大小的数组:

Dim arr() As Double
ReDim arr(1 To test_sheet.Range("F2:F278").Count)
Dim i As Long
For i = LBound(arr) To UBound(arr)
    arr(i) = max_val
Next

ser.XValues = test_sheet.Range("F2:F278")
ser.Values = arr
© www.soinside.com 2019 - 2024. All rights reserved.