XY散点图和字典问题

我有一个函数可以根据任意数量的字典(每个字典代表图表上的一行)生成XY散点图,每个字典都包含date键和数字值。 到目前为止,这些值似乎在Y轴上工作,但date轴(X)似乎被打破。 每次我把这个系列添加到字典中的graphics,当我特别想要一个散点图的时候,它会强制它成为一个条形图。 如果我在分配它后强制回到散点图,它完全拒绝显示date轴。

这里有些例子。

我希望图表看起来像这样 在这里输入图像说明

如果我告诉它不使用date,图表看起来像这样

在这里输入图像说明

当我将该系列的数据types专门设置为xlDate时,graphics将更改为此。 它神秘地变成了一个条形图

在这里输入图像说明

如果我在将它设置为使用xlDate后专门将其更改回散点图,则如下所示

在这里输入图像说明

任何帮助将非常感激。 这是我的VBA代码

Sub GenerateProgressGraph() Dim Dictionaries(1 To 2) As New Dictionary Dictionaries(1).Add DateValue("1/2/2012"), 1 Dictionaries(1).Add DateValue("2/2/2012"), 2 Dictionaries(1).Add DateValue("3/2/2012"), 3 Dictionaries(1).Add DateValue("4/2/2012"), 4 Dictionaries(2).Add DateValue("1/2/2012"), 1 Dictionaries(2).Add DateValue("2/2/2012"), 1 Dictionaries(2).Add DateValue("3/2/2012"), 3 Dictionaries(2).Add DateValue("4/2/2012"), 4 Call ProcessProgressGraph(Dictionaries) End Sub Sub ProcessProgressGraph(Dict() As Dictionary) Dim Graph As Shape Dim GraphRange As Range With ActiveSheet 'set graph area Set GraphRange = Application.Range("E4:P21") 'add a new chart Set Graph = Shapes.AddChart(xlXYScatterLinesNoMarkers, GraphRange.Left, _ GraphRange.Top, GraphRange.Width, GraphRange.Height) With Graph.Chart With .Axes(xlCategory) .HasTitle = True .AxisTitle.Characters.Text = "Dates" End With .HasTitle = True .ChartTitle.Text = "Chart Title" .ChartType = xlXYScatterLinesNoMarkers 'clear all chart data '(Excel has a tendency to give us silly resultsets by default) For Each srs In .SeriesCollection srs.Delete Next For Each Dictionary In Dict Dim ss As Series Set ss = .SeriesCollection.NewSeries ss.Name = "Values" ss.XValues = Dictionary.Keys ss.Type = xlDate .ChartType = xlXYScatterLinesNoMarkers 'this forces it back into a scatter plot since it auto makes a bar graph ss.Values = Dictionary.Items Next End With End With End Sub 

问题在于Excel的本机处理X轴值。 说实话,我不知道为什么会发生这种情况,但我知道如何解决这个问题:

  1. 获取你的X轴date值,并使用类似这样的方法将它们转换为Longtypes:

     ReDim longDates(Dictionary.Count) as Long For i = LBound(Dictionary.Keys) to UBound(Dictionary.Keys) longDates(i) = Dictionary.Keys(i) Next 
  2. 使用ss.XValues = longDates将longDates分配为X轴值

  3. 使用以下命令将TickLabel数字格式设置为函数末尾的date:

     .Axes(xlCategory).TickLabels.NumberFormat = "d/mm/yyyy" 

这应该工作