如何在图表上使用日期为XValues的数组值? (VBA)

时间:2017-04-18 15:41:44

标签: arrays vba date charts

我有一个图表,我从图表中绘制了2个系列。 对于每个系列,我尝试将XValues设置为数组的第一个维度,即日期。

我的问题是图表X轴上显示的日期是00/01/1990等日期,而不是我的数组中的日期(我检查了这些日期)。 如何在图表上显示正确的日期?

我执行以下操作:

Set ch = ws.Shapes.AddChart(Width:=1000, Height:=500, Left:=ws.Columns("B").Left, Top:=ws.Range("B66").Top).Chart
    With ch
        .ChartType = xlXYScatterLines
        .HasTitle = True
        .ChartTitle.Text = "TITLE"

        For i = 1 To 2
            Set s = .SeriesCollection.NewSeries
            With s
                .Values = Application.Index(vD, , i + 1)
                If i = 1 Then
                    .Name = "S1"
                    .ChartType = xlXYScatterLines
                ElseIf i = 2 Then
                    .AxisGroup = 2
                    .Name = "S2"
                    .ChartType = xlColumnStacked
                End If
                .XValues = ws.Application.Index(vD, , 1)
            End With
        Next i
        .Axes(xlCategory, xlPrimary).CategoryType = xlTimeScale
        .Axes(xlCategory, xlPrimary).TickLabels.NumberFormat = "dd/mm/yyyy" 
    End With

编辑:vD是一个变体,其中我将我的3个系列中的2个图表作为值,而图表作为XValues(日期)。

所以vD看起来像这样:

|   1      |   2   |   3  |
|2017-01-01|   12  |  115 |
|2017-01-02|   15  |  101 |
|2017-01-03|   11  |  125 |
|2017-01-04|   12  |  139 |
...

然后第一个系列图是第二列,然后是第三列,每次我将变量的第一列添加为XValues。

1 个答案:

答案 0 :(得分:0)

尝试修改后的代码(代码注释中的解释):

Set ch = ws.Shapes.AddChart(Width:=1000, Height:=500, Left:=ws.Columns("B").Left, Top:=ws.Range("B9").Top).Chart
With ch
    .ChartType = xlXYScatterLines
    .HasTitle = True
    .ChartTitle.text = "TITLE"

    For i = 1 To 2
        Set s = .SeriesCollection.NewSeries
        With s
            ' ===== THIS IS THE PART I'VE MODIFIED =====
            ' Values in Range "B1:B4" for 1st series, and in Range "C1:C4" for 2nd series
            .Values = "=" & ws.Range(ws.Cells(1, i + 1), ws.Cells(4, i + 1)).Address(True, True, xlA1, xlExternal)
            ' XValues in Range "A1:A4" for both series
            .XValues = "=" & ws.Range(ws.Cells(1, 1), ws.Cells(4, 1)).Address(True, True, xlA1, xlExternal)

            If i = 1 Then
                .Name = "S1"
                .ChartType = xlXYScatterLines
            ElseIf i = 2 Then
                .AxisGroup = 2
                .Name = "S2"
                .ChartType = xlColumnStacked
            End If                
        End With
    Next i
    .Axes(xlCategory, xlPrimary).CategoryType = xlTimeScale
    .Axes(xlCategory, xlPrimary).TickLabels.NumberFormat = "dd/mm/yyyy"
End With