避免在Excel中选择VBA仍然无法加速我的代码

问题描述 投票:0回答:2

这是我第一次在StackExchange上找不到问题的答案。你们这些人非常彻底。无论如何,我们最近从2007年更新到Office 365 / Excel 2016,现在我的VBA脚本将不会运行,除了一夜之间。我研究并了解到使用Select / Activate是一个可怕的人。我已经看到了我的方式的错误,但现在即使是简单的代码仍然不想在大表上运行。我的代码,它清除当前工作表中的格式,以便更快地填充数据:

Sub ClearFormattingAndValidation()

Dim referenceCell As Range
Dim rngToFormat As Range

With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
    .EnableEvents = False
End With

Set referenceCell = Cells.Find("Some specific text", after:=ActiveCell, LookAt:=xlWhole)

Set rngToFormat = Range(referenceCell.Offset(2, 0), ActiveCell.SpecialCells(xlLastCell))
'    rngToFormat.Select

With rngToFormat
    .Validation.Delete 'near-instantaneous
    .FormatConditions.Delete 'took 7-15 minutes on timed runs
End With

With Application
    .ScreenUpdating = True
    .Calculation = xlCalculationAutomatic
    .EnableEvents = True
End With

End Sub

当我取消注释rngToFormat.Select时,我总共获得了76,302个单元格,以便您了解电子表格的大小。有很多验证和条件格式。在2007年,即使使用选择/选择,它也会在几秒钟内完成。现在,我不知道需要多长时间。我在5分钟后放弃了。它确实在较小版本的工作表上成功运行。

如果可能的话,我想避免删除验证和条件格式化,但如果这是加速它的唯一方法,那么对于大约一半它来说它是一个(耗时且昂贵的)可能性。

还有什么我可以做的,以使代码运行得更快,或者有什么我做错了吗?

编辑:代码已更改,以反映截至2/21的评论/建议。类似的结果。

excel vba excel-vba
2个回答
1
投票

您的代码可以立即使用Excel 2013运行。

虽然代码可以写成如下...

Sub ClearFormattingAndValidation()
Dim referenceCell As Range
Dim rngToFormat As Range

With Application
    .Calculation = xlCalculationManual
    .EnableEvents = False
    .ScreenUpdating = False
End With
Set referenceCell = Cells.Find("Some specific text", after:=ActiveCell, LookAt:=xlWhole)

If Not referenceCell Is Nothing Then
    Set rngToFormat = Range(referenceCell.Offset(2, 0), ActiveCell.SpecialCells(xlLastCell))
    With rngToFormat
        .FormatConditions.Delete
        .Validation.Delete
    End With
End If

With Application
    .Calculation = xlCalculationAutomatic
    .EnableEvents = True
    .ScreenUpdating = True
End With
End Sub

0
投票
With ActiveSheet
    .EnableFormatConditionsCalculation = False
End With

这会禁用导致减速的条件格式。运行代码后应该重新启用它。

再次感谢,@ sktneer。你的帮助把我推向正确的方向。

© www.soinside.com 2019 - 2024. All rights reserved.