-2

我正在尝试在从表中接收 5 系列数据的图表上自动插入一条水平线。每一天,我都会在该表中添加另一行值。我想在从这 5 个系列获得的图表中插入一条水平线,该水平线从其中一个系列的最后一个值更新(其 y 坐标),表示过去 30 天的飞水消耗量。我想在 Excel 工作簿中使用 VBA。我可以寻求帮助吗?谢谢你。

在此处输入图像描述

该图将是这样的: 在此处输入图像描述

4

1 回答 1

0

如果添加额外的列不可行,请尝试以下代码:

Sub SubExtraLine()
    
    'Declarations.
    Dim ObjChart As Object
    Dim RngCell As Range
    Dim DblCounter As Double
    Dim VarSeries As Variant
    Dim ObjSeries As Object
    Dim StrSeriesName As String
    
    'Settings.
    Set RngCell = Range("D1").End(xlDown) '‹ Specify here the cell with the value.
    Set ObjChart = Shapes("Chart 1") '‹ Specify here the chart.
    StrSeriesName = "Consumo em 30 dias" '‹ Specify here the name of the line.
    
    'Checking the maximum number of values for each series of ObjChart.
    For Each VarSeries In ObjChart.Chart.SeriesCollection
        DblCounter = Excel.WorksheetFunction.Max(DblCounter, UBound(VarSeries.Values))
        'If a series named as StrSeriesName already exists, it's deleted.
        If VarSeries.Name = StrSeriesName Then
            VarSeries.Delete
        End If
    Next
    
    'Setting VarSeries as the formula for the new series.
    Set VarSeries = Nothing
    VarSeries = "="
    For DblCounter = DblCounter To 1 Step -1
        VarSeries = VarSeries & RngCell.Parent.Name & "!" & RngCell.Address & ","
    Next
    VarSeries = Left(VarSeries, Len(VarSeries) - 1)
    
    'Creating the new series.
    Set ObjSeries = ObjChart.Chart.SeriesCollection.NewSeries
    ObjSeries.Name = "=""" & StrSeriesName & """"
    ObjSeries.Values = VarSeries
    
End Sub
于 2021-01-20T18:01:27.487 回答