VBA优化了3个循环的性能

时间:2017-06-05 02:45:25

标签: excel vba excel-vba loops optimization

首先,我想检查" Sheet1"的第D列的每一行中的值。匹配"接受"的A列的任何一行。如果匹配,我想复制" Sheet1"的那一行的B列中的值。进入"接受"。

的D栏

但是,由于" Sheet1"的B列中有2个可能的值,我想将这些值拆分为两列"接受" - 列D和E.因此,下一个循环,如果列D中的值为"接受"不是"受限制",然后将该值复制到E列并删除D列的内容。

代码工作得很好,因为它帮助我实现了我的目标,然而,这个过程耗时太长,经过一些调查后我发现延迟只发生在最后一个循环中。我想知道我是否可以加快这个过程,谢谢!

Dim i As Long
Dim j As Long
Dim k As Long

'to speed up the VBA code
With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
End With


AcceptedLastRow = ActiveWorkbook.Worksheets("Accepted").Range("A" & Rows.Count).End(xlUp).Row
Sheet1LastRow = ActiveWorkbook.Worksheets("Sheet1").Range("D" & Rows.Count).End(xlUp).Row

    For j = 1 To AcceptedLastRow
        For i = 1 To Sheet1LastRow
            If ActiveWorkbook.Worksheets("Sheet1").Cells(i, 4).Value = ActiveWorkbook.Worksheets("Accepted").Cells(j, 1).Value Then
            ActiveWorkbook.Worksheets("Accepted").Cells(j, 4).Value = ActiveWorkbook.Worksheets("Sheet1").Cells(i, 2).Value    
            End If
        Next i
    Next j

'to transfer recognised status to the recognised column and to remove from restricted column
'I think this is the section which contributes to the lag/delay
Restrictedlastrow = ActiveWorkbook.Worksheets("Accepted").Range("D" & Rows.Count).End(xlUp).Row
    For k = 9 To Restrictedlastrow
        If ActiveWorkbook.Sheets("Accepted").Cells(k, 4).Value <> "Restricted" Then
        ActiveWorkbook.Sheets("Accepted").Cells(k, 4).Copy ActiveWorkbook.Sheets("Accepted").Cells(k, 5)
        ActiveWorkbook.Sheets("Accepted").Cells(k, 4).ClearContents
        End If
    Next k


'to reset settings back to normal
With Application
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
End With

1 个答案:

答案 0 :(得分:1)

而不是

ActiveWorkbook.Sheets("Accepted").Cells(k, 4).Copy ActiveWorkbook.Sheets("Accepted").Cells(k, 5)

使用

ActiveWorkbook.Sheets("Accepted").Cells(k, 5) = ActiveWorkbook.Sheets("Accepted").Cells(k, 4)

复制是一项昂贵的操作。由于您似乎只对单元格的值感兴趣,因此请直接指定它(就像您在之前的循环中所做的那样)。