Excel VBA嵌套循环效率

时间:2016-09-09 17:57:01

标签: arrays excel vba excel-vba nested-loops

我希望提高此Excel VBA嵌套循环的速度。循环比较从一张纸到二张纸的日期。如果它们匹配,我会更改单元格周围的边框以突出显示它。它目前工作正常,但每个子处理大约需要30秒。有没有办法实现数组或其他策略来加快它?提前谢谢!

public static boolean isSTAGING() {
    checkLoadedYet();
    return isSTAGING;
}

1 个答案:

答案 0 :(得分:0)

您是否尝试在代码之上使用Application.ScreenUpdating = False,然后在底部使用Application.ScreenUpdating = True?它会禁用屏幕更新,我的宏会更快很多。您还可以禁用其他设置(然后重新启用),例如参见this website

<小时/> 在评论OP Application.ScreenUpdating = False没有提高速度后更新:

我稍微改变了你的代码,看到了一些提速。您的代码通常需要大约0.65秒才能完成,我的代码大约需要0.51秒。这段代码能为你加快速度吗?

Sub SingleIsAnIdentifier_SoItCannotBeUsedAsASubName()

Dim DateRng As Range, DateCell As Range, DateRngPay As Range
Dim cellA As Range
Dim cellB As Range
Dim myColor As Integer

Dim RngToColor As Range 'Range to hold all cells to give a colored border.

Set DateRng = ActiveWorkbook.Worksheets("SS").Range("B11:F16,I11:M16,P11:t16,B19:F24,I19:M24,P19:t24,B27:F32,I27:M32,P27:t32,B35:F40,I35:M40,P35:t40")
Set DateRngPay = ActiveWorkbook.Worksheets("PS").Range("C2:C67")
myColor = 38

If ActiveWorkbook.Worksheets("Info").Range("B67") = 1 Then
    With DateRng
            .Interior.ColorIndex = xlColorIndexNone
            '.Borders.LineStyle = xlContinuous
            .Borders.ColorIndex = 1
            .Borders.Weight = xlHairline
    End With
    For Each cellA In DateRng
        For Each cellB In DateRngPay
            If cellB.Value > "" And cellA.Value > "" And cellB.Value = cellA.Value Then

                ' Add cellA to the range. The range will be colored later.
                If Not RngToColor Is Nothing Then
                    Set RngToColor = Union(RngToColor, cellA)
                Else
                    Set RngToColor = cellA
                End If

            End If
        Next cellB
    Next cellA
End If

' Color all cells in the range.
With RngToColor.Cells.Borders
    .ColorIndex = myColor
    .Weight = xlMedium
End With

End Sub

我没有在cellA时立即着色cellA.value = cellB.value的边框,而是将cellA保存在另一个范围内(RngToColor)。在代码的最后,我为该范围内的所有边框着色。此外,Dim myColor As Variant及更晚myColor = Array("38")对我无效(.ColorIndex = myColor正在投诉),因此我将其更改为Integer