Excel VBA用数组replace循环以获得性能增益

今天早些时候,我在开发一些代码的过程中得到了一些帮助,这些代码将把一个单元格的内容放在一个注释中,当它被隐藏时可以显示出来。

它工作的很好,但在6000行的电子表格上可能需要一段时间。 我在这里读到,你可以用数组逻辑代替循环逻辑来加速这个过程。

任何想法,我会开始把这从基于循环的基于数组?

Dim iCell As Range On Error Resume Next 'included because of an error when the .Formula function was triggered For Each iCell In Selection With iCell If CStr(.Value) <> "" Then .ClearComments .AddComment .Comment.Visible = False .Comment.Text Text:=CStr(.Value) .Comment.Shape.ScaleWidth 5.87, msoFalse, msoScaleFromTopLeft .Comment.Shape.ScaleHeight 5.87, msoFalse, msoScaleFromTopLeft '2.26 was the original height End If If .Formula <> "" Then .ClearComments .AddComment .Comment.Visible = False .Comment.Text Text:=CStr(.Formula) .Comment.Shape.ScaleWidth 5.87, msoFalse, msoScaleFromTopLeft .Comment.Shape.ScaleHeight 5.87, msoFalse, msoScaleFromTopLeft End If End With Next End Sub 

和上次一样,任何和所有的帮助都会受到赞赏,无论是指导还是示例还是解决scheme – 我都试图对其进行反向工程,从而更多地了解这些东西。 谢谢!

这是一个如何改善您的必要范围循环的例子:

  1. 使用SpecialCells来处理公式,而无需查看每个单元格。
  2. 优化Application设置。
  3. 将隐藏注释的行放在循环之外。

 Sub Recut() Dim rng1 As Range Dim rng2 As Range Dim lngCalc As Long 'look only at formulae On Error Resume Next Set rng1 = Selection.SpecialCells(xlFormulas) On Error GoTo 0 If rng1 Is Nothing Then Exit Sub 'Improve application settings for speed With Application lngCalc = .Calculation .ScreenUpdating = False .Calculation = xlCalculationManual .DisplayAlerts = False End With For Each rng2 In rng1.Cells With rng2 .ClearComments .AddComment .Comment.Text Text:=CStr(.Formula) .Comment.Shape.ScaleWidth 5.87, msoFalse, msoScaleFromTopLeft .Comment.Shape.ScaleHeight 5.87, msoFalse, msoScaleFromTopLeft End With Next 'take comment display out of the loop Application.DisplayCommentIndicator = xlCommentIndicatorOnly With Application .ScreenUpdating = True .Calculation = lngCalc .DisplayAlerts = True End With End Sub