为什么格式化辅助轴会导致错误?

我创build了一个从数据数组创build图表的函数。 有时候它可以正常工作,有时候不会,原因不明。 如果没有,则会出现以下错误:

运行时错误“-2147467259(80004005)”

我试图尽可能地减less代码,同时仍然“保存”这个问题。 缩减的代码如下。 它从下面的第三行错误。 如果在指定的位置使用DoEvents语句,那么它的错误就会less得多,但有时候也是如此。 我正在使用Excel 2007。

我的问题是:

  1. 这里有什么问题?
  2. 该怎么办,因为添加DoEvents不是一个完整的解决scheme。 另外,我读过DoEvents经常被认为是相当邪恶的。

Option Explicit Sub test() Dim a(1 To 3) As Double Dim b(1 To 3) As Double Dim c(1 To 3) As Double Dim d(1 To 3) As Double a(1) = 1.1 a(2) = 1.3 a(3) = 0.8 b(1) = 1.1 b(2) = 1.3 b(3) = 0.8 c(1) = 1.1 c(2) = 1.3 c(3) = 0.8 d(1) = 1.1 d(2) = 1.3 d(3) = 0.8 Call PrintSimChart(a, b, c, d) End Sub Function PrintSimChart(a() As Double, b() As Double, c() As Double, d() As Double) 'Prints given simulation result to chart Dim SimChart As Chart 'Create a new chart. Set SimChart = Charts.Add With SimChart With .SeriesCollection.NewSeries .Values = a .XValues = b .ChartType = xlColumnStacked End With With .SeriesCollection.NewSeries .Values = c .XValues = d ' DoEvents 'Not adding this line causes a crash on line: .Axes(xlCategory, xlSecondary).TickLabels.NumberFormat = "dd/mm/yyyy" .ChartType = xlXYScatterLinesNoMarkers .Format.Line.Weight = 1 End With .Axes(xlCategory).CategoryType = xlTimeScale .Axes(xlCategory, xlPrimary).TickLabels.NumberFormat = "dd/mm/yyyy" .Axes(xlCategory, xlSecondary).TickLabels.NumberFormat = "dd/mm/yyyy" End With End Function 

这是我发现的可靠工作的最小的解决scheme。 需要两条额外的线来解决这个问题。

 Function PrintSimChart(a() As Double, b() As Double, c() As Double, d() As Double) 'Prints given simulation result to chart Dim SimChart As Chart 'Create a new chart. Set SimChart = Charts.Add With SimChart With .SeriesCollection.NewSeries .ChartType = xlColumnStacked .Values = a .XValues = b End With With .SeriesCollection.NewSeries .ChartType = xlXYScatterLinesNoMarkers .Values = c .XValues = d .AxisGroup = xlSecondary '**Required Edit** .Format.Line.Weight = 1 End With With .Axes(xlCategory, xlPrimary) .CategoryType = xlTimeScale .TickLabels.NumberFormat = "dd/mm/yyyy" End With .HasAxis(xlCategory, xlSecondary) = True '**Required Edit** .Axes(xlCategory, xlSecondary).TickLabels.NumberFormat = "dd/mm/yyyy" End With End Function