performance - VBA 图表操作缓慢

标签 performance vba excel

我编写了一些 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

删除网格、更改标题、绘制 X 和 Y 系列以及删除图例似乎需要很长时间。我用谷歌搜索了编写代码的替代方法,但没有找到任何有用的东西。除了速度较慢之外,代码完全按预期工作。关于导致性能不佳的原因以及如何加快速度有什么想法吗?提前致谢。

编辑:我在使用图表时已经关闭了屏幕更新。图表是在用户表单打开时生成/格式化的(如果这有什么区别的话)。

这是相关的代码片段:

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

最佳答案

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

我要更改的首要事项是激活图表。如果您通过代码创建图表,请执行此操作,但将其设置为变量,例如 Set wcChart = ThisWorkbook.Charts.Add。然后将 With ActiveChart 更改为 With wcChart

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

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

要尝试的其他更改,我并不是说这些会起作用,但如果您还没有尝试过,那么它们值得一试。而不是每次都检查 FullSeriesCollection:

Do While .FullSeriesCollection.Count > 0
    .FullSeriesCollection(1).Delete
Loop

以下可能会更快:

For ii = .FullSeriesCollection.Count To 1 Step -1
    .FullSeriesCollection(ii).Delete
Next ii

此外,我使用以下内容代替图表标题和网格线的 .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

关于performance - VBA 图表操作缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19341202/

相关文章:

c++ - 乘法比浮点除法快吗?

java - 在应用服务器上部署多个应用程序(weblogic/websphere)

vba - Excel VBA - 用户定义类实例的公共(public)范围

使用动态范围时出现 VBA 错误

c - 哪个运算符更快(> 或 >=)、(< 或 <=)?

vba - 在 Excel 公式中引用 float 列 (VBA)

r - 从 PowerPivot 导出数据

vba - 在 Excel 表中自动更新数据时返回确切更新内容的消息

excel - 我怎样才能让智能感知为 XLAM 文件中的 UDF 工作?

java - 静态方法作为独立类更慢?