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