excelvbacharts

I dont want to extract data of chart from excel cells


The following code works perfectly.

Public Sub Macro1()

'Enter Today's date into A1 and A2 cells.
ActiveSheet.Range("A1").Value = Now()
ActiveSheet.Range("A2").Value = Now()

'Add a chart.
With ActiveSheet.ChartObjects.Add(Left:=100, Top:=50, Width:=400, Height:=200)
    .Name = "myChart"
End With

'Add a xlLine serie.
With ActiveSheet.ChartObjects("myChart").Chart.SeriesCollection.NewSeries
    .ChartType = xlLine
    .Name = "Example"
    .Values = Array(100, 200, 300, 400, 500, 600)
    .XValues = Array(45658, 45689, 45717, 45748, 45778, 45809)
End With
    
End Sub

I dont want to extract data of chart from excel cells.

So I tried to replace this

.XValues = ActiveSheet.Range("A1:A2")

with this

.XValues = Array(Now(), Now())

But this time output of chart is corrupted.

How can I solve that problem?


Solution

  • As already written as comment:

    When writing .XValues = Array(Now(), Now()), the date is implicitly converted into a string (a formatted date). Couldn't find any documentation about it, just observed it using your code:

    enter image description here

    When displaying the data, Excel tries to fit that value onto the x-axis. As this axis contains dates, the string is converted back to a numeric value but fails, so Excel assumes the value "0". It expands the x-Axis so that is starts at 0 (=1.1.1900) and puts the series to the very left.

    Easiest way is to pass the numeric representation values to the chart (as you already for the x-axis).

    .XValues = Array(CLng(Now), CLng(Now))