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

时间:2013-11-25 15:18:43

标签: excel excel-vba charts excel-2007 vba

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

运行时错误'-2147467259(80004005)'

我试图尽可能地减少代码,同时仍“保存”问题。简化代码如下。它从下面第三行出错。如果在指定的位置使用DoEvents语句,则它的错误频率会低得多,但有时仍会出错。我正在使用Excel 2007。

我的问题是:

  1. 这里有什么问题?
  2. 如何处理它,因为添加DoEvents不是一个完整的解决方案。另外,我读过DoEvents通常被认为是非常邪恶的。

  3. 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
    

1 个答案:

答案 0 :(得分:1)

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

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