时间序列值与我的Excel图表上的水平轴不匹配

时间:2019-05-27 07:07:07

标签: excel vba charts

通过使用X-Y图代替线形图来解决

我想在Excel中创建一个图表,其中包含按日期链接的多个系列(即,一个系列在2018/12/31结束,下一个系列在2018/12/31开始)。原始数据取自具有两列的工作表;日期列和值列。

此处涉及的图表称为“测试版”,包含3个时间序列。 这是我的尝试:

Sub UpdateGraph
Dim ws             As Worksheet
Dim rng_NF3        As Range
Dim rng_Barra      As Range
Dim rng_NF3_Date   As Range
Dim rng_Barra_Date As Range
Dim rng_Total_Date As Range
Dim rng_Total_Val  As Range
Dim cht_Name       As String
Dim ArrDate        As Variant
Dim arrValues      As Variant


        cht_Name = "Beta"  ' Example
        Set ws = Activesheet
        Set cht = ws.ChartObjects(cht_Name)
        Set rng_NF3 = ws.Range(ws.Cells(2, 4), ws.Cells(200, 4)) ' Set range of values from NF3 (GEM3)
        Set rng_Barra = ws.Range(ws.Cells(201, 4), ws.Cells(500, 4)) ' Set range of values Barra
        Set rng_NF3_Date = rng_NF3.Offset(0, -1) ' Set range of date for NF3 observations
        Set rng_Barra_Date = rng_Barra.Offset(0, -1) ' Set range of date for Barra observations
        Set rng_Total_Date = Union(rng_NF3_Date, rng_Barra_Date)
        Set rng_Total_Val = Union(rng_NF3, rng_Barra)
        ArrDate = rng_Total_Date.Value
        arrValues = rng_Total_Val.Value
        With cht.Chart
            .FullSeriesCollection(1).Format.Line.ForeColor.RGB = ws.Cells(1, 20).Interior.Color
            .FullSeriesCollection(2).Format.Line.ForeColor.RGB = ws.Cells(2, 20).Interior.Color
            .FullSeriesCollection(1).Values = rng_NF3 ' Value series for NF3
            .FullSeriesCollection(2).Values = rng_Barra ' Value series for Barra
            .FullSeriesCollection(1).XValues = rng_NF3_Date
            .FullSeriesCollection(2).XValues = rng_Barra_Date
             If cht_Name = "Beta" Then ' Defining Beta = 1
             .FullSeriesCollection(3).Format.Line.ForeColor.RGB = ws.Cells(1, 21).Interior.Color '  Color
             .FullSeriesCollection(3).Values = 1 ' Should be a range with the same number in all elements, not working but another issue.
             .FullSeriesCollection(3).XValues = rng_Total_Date
             End If
             ' X-axis
             With cht.Chart.Axes(xlCategory)
                .CategoryType = xlTimeScale
                '.MajorUnitScale = xlMonths
                .MinimumScale = ArrDate(LBound(ArrDate, 1), 1)
                .MaximumScale = ArrDate(UBound(ArrDate, 1), 1)
                .MajorUnit = 3 ' Manually set x-axis unit scale
                '.MajorUnitIsAuto = True
             End With
            ' Y-axis
            With cht.Chart.Axes(xlValue)
                .MinimumScaleIsAuto = True
                .MaximumScaleIsAuto = True
                .MajorUnitIsAuto = True
            End With
        End With

End sub

我希望该系列彼此继续,但相反,它们都在水平轴的第一个日期开始。我怀疑Excel无法识别我将时间序列日期与x轴日期匹配的尝试。

这是我的身材。我正在使用折线图。 enter image description here

1 个答案:

答案 0 :(得分:0)

@TimWilliams提供的答案,如果他没有创建帖子,我将在可能的情况下将其标记为答案。

解决方案是使用X-Y散点图(可用折线图)代替我最初使用的折线图。