O código a seguir funciona perfeitamente.
Public Sub Macro1()
'Enter Today's date into A1 and A2 cells.
ActiveSheet.Range("A1").Value = Now()
ActiveSheet.Range("A2").Value = Now()
'Delete all charts
For i = ActiveSheet.Shapes.Count To 1 Step -1
If ActiveSheet.Shapes(i).Type = msoChart Then
ActiveSheet.Shapes(i).Delete
End If
Next i
'Add a chart.
With ActiveSheet.ChartObjects.Add(Left:=100, Top:=50, Width:=400, Height:=200)
.Name = "myChart"
.Chart.Axes(xlCategory).CategoryType = xlTimeScale
.Chart.Axes(xlCategory).TickLabels.NumberFormat = "MMM/YY"
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
'Add a xlXYScatterLinesNoMarkers serie.
With ActiveSheet.ChartObjects("myChart").Chart.SeriesCollection.NewSeries
.ChartType = xlXYScatterLinesNoMarkers
.Name = "My Birthday"
.Values = Array(0, 800)
.XValues = ActiveSheet.Range("A1:A2")
'Points settings
.Points(1).ApplyDataLabels
.Points(1).DataLabel.ShowSeriesName = True
.Points(1).DataLabel.ShowCategoryName = False
.Points(1).DataLabel.ShowValue = False
.Points(1).DataLabel.Position = xlLabelPositionAbove
.Points(1).DataLabel.Orientation = xlUpward
.Points(1).DataLabel.Width = 200
.Points(1).DataLabel.Format.TextFrame2.AutoSize = msoAutoSizeShapeToFitText
End With
End Sub
Não quero extrair dados do gráfico de células do Excel.
Então eu tentei substituir isso
.XValues = ActiveSheet.Range("A1:A2")
com isso
.XValues = Array(Now(), Now())
Mas desta vez a saída do gráfico está corrompida.
Como posso resolver esse problema?
Como já escrito como comentário:
Ao escrever
.XValues = Array(Now(), Now())
, a data é implicitamente convertida em uma string (uma data formatada). Não consegui encontrar nenhuma documentação sobre isso, apenas observei usando seu código:Ao exibir os dados, o Excel tenta encaixar esse valor no eixo x. Como esse eixo contém datas, a string é convertida de volta para um valor numérico, mas falha, então o Excel assume o valor "0". Ele expande o eixo x para que comece em 0 (=1.1.1900) e coloque a série bem à esquerda.
A maneira mais fácil é passar os valores de representação numérica para o gráfico (como você já fez para o eixo x).