Excel VBA用数组替换循环以获得性能提升

时间:2016-02-05 04:06:37

标签: arrays excel vba excel-vba

今天早些时候,我得到了一些帮助,可以开发一些代码,这些代码可以获取单元格的内容并将其放在注释中,这些注释可以在被鼠标悬停时显示。

效果很好,但在6000行电子表格中可能需要一段时间。我读了here,你可以用数组逻辑替换循环逻辑,以加快这个过程。

我知道从哪里开始将其从基于循环的转变为基于数组?

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

与上次一样,任何和所有帮助都表示赞赏,无论是指导或示例还是解决方案 - 我打算尝试对其进行逆向工程,以便更多地了解这些内容。谢谢!

1 个答案:

答案 0 :(得分:2)

这是一个如何改进必要范围循环的示例:

  1. 使用SpecialCells处理公式而不查看每个单元格。
  2. 优化Application设置。
  3. 将隐藏评论的行排除在循环之外。
  4. 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