VBA图表操纵缓慢

Mat*_*t P 5 excel performance vba excel-vba

我写了一些Excel VBA代码,它生成一个散点图并更改了图表的一些属性.(代码如下所示.)代码缓慢移动通过删除图表图例,删除水平/垂直网格线以及更改X和Y系列等任务.Excel的计时器为每个任务提供以下持续时间:

insert scatterplot: 0.01171875 
delete series: 0 
plot x vs y: 0.55859375 
delete legend: 0.5703125 
delete chart title: 0.66015625 
remove grid: 1.3046875 
format axes: 0 
overall: 3.11328125
Run Code Online (Sandbox Code Playgroud)

删除网格,更改标题,绘制X和Y系列以及删除图例似乎需要很长时间.我已经google搜索代码的其他方法,但一直找不到任何有用的东西.代码完全按预期工作,除了速度慢.关于导致糟糕表现的原因以及我如何加快速度的想法?提前致谢.

编辑:我已经在使用图表时关闭了屏幕更新.在用户表单打开时生成/格式化图表,如果这有任何区别.

以下是相关的代码片段:

With ActiveChart
    'Delete all series currently in plot
    Do While .FullSeriesCollection.Count > 0
        .FullSeriesCollection(1).Delete
    Loop

    'Plot Actual (Y) vs. Inverse Distribution (X)
    .SeriesCollection.NewSeries
    .FullSeriesCollection(1).XValues = "=" & tempSheetName & "!$C:$C"
    .FullSeriesCollection(1).Values = "=" & tempSheetName & "!$A:$A"

    'Delete legend
    .Legend.Delete

    'Delete chart title
    .SetElement (msoElementChartTitleNone)

    'Remove gridlines
    .SetElement (msoElementPrimaryValueGridLinesNone)
    .SetElement (msoElementPrimaryCategoryGridLinesNone)

    'Format axes
    Dim xAxis As Axis, yAxis As Axis
    Set xAxis = .Axes(xlCategory)
    Set yAxis = .Axes(xlValue)

    With yAxis
        'Title y axis "actual"
        .HasTitle = True
        .AxisTitle.Caption = "Actual"

        'Add tick marks
        .MajorTickMark = xlOutside
    End With

    With xAxis
        'Title x axis by dist type
        .HasTitle = True
        .AxisTitle.Caption = dist.getDistType

        'Add tick marks
        .MajorTickMark = xlOutside
    End With
End With
Run Code Online (Sandbox Code Playgroud)

Cub*_*ase 2

如果没有数据和机器细节,很难说为什么这么慢,尽管这里有一些代码的替代方案。

我要更改的首要也是最重要的事情是激活图表。如果您通过代码创建图表,请这样做,但将其设置为变量,例如Set wcChart = ThisWorkbook.Charts.Add。然后更改With ActiveChartWith wcChart.

另外,删除FullSeriesCollection然后删除图表标题,删除网格线并更改轴,然后再填充新数据。图表中的数据较少,图表操作应该更快。但这里要小心,因为以不同顺序更改图表的各个方面可能会产生不同的输出(例如图例的布局)。

您用 A 和 C 的整个列填充新数据FullSeriesCollection,指定数据的确切范围而不是整个列。

其他可以尝试的改变,我并不是说这些会起作用,但如果你还没有尝试过,它们值得一试。而不是FullSeriesCollection每次都检查 a:

Do While .FullSeriesCollection.Count > 0
    .FullSeriesCollection(1).Delete
Loop
Run Code Online (Sandbox Code Playgroud)

以下可能会更快:

For ii = .FullSeriesCollection.Count To 1 Step -1
    .FullSeriesCollection(ii).Delete
Next ii
Run Code Online (Sandbox Code Playgroud)

另外,.SetElement我使用以下内容代替图表标题和网格线:

'You have to set the title to 'True' before it'll work with 'False'.  Go figure.
.HasTitle = True
.HasTitle = False

.HasMajorGridlines = False
.HasMinorGridlines = False
Run Code Online (Sandbox Code Playgroud)