How to efficiently run through rows of data to match a criterion using excel VBA?

时间:2018-06-04 17:35:58

标签: excel-vba vba excel

Normally what I do on my program is using logic like:

Total_rows_worksheet = Worksheets("Sample").Range("A" & Rows.Count).End(xlUp).Row
For i = 2 to Total_rows_worksheet
    If Worksheets("Sample").Cells(i,1)=Criteria Then
       [Perform this action]
    End If
Next i

However, when the number of rows get large, code that runs through the entire sheet gets a bit slow. Also, I remember my programmer friend telling me that it is a common mistake for beginner programmers to run through all the data. The correct way according to him was to point to the rows of interest, but I do not know exactly how to do that in Excel.

2 个答案:

答案 0 :(得分:1)

在循环之前禁用屏幕更新和计算,它将极大地提高速度。

Sub testing()
    'Disable screen updating and calculation
    Dim uRange As Range
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Total_rows_worksheet = Worksheets("Sample").Range("A" & Rows.Count).End(xlUp).Row
    For i = 1 To Total_rows_worksheet
        If Worksheets("Sample").Cells(i, 1) = "OK" Then
            If uRange Is Nothing Then
                Set uRange = Worksheets("Sample").Cells(i, 1)
            Else
                Set uRange = Union(uRange, Worksheets("Sample").Cells(i, 1))
            End If
        End If
    Next i
    uRange.Value = "THIS USED TO SAY OK"
    'Enable screen updating and calculation when done
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

编辑1:根据任务的不同,另一种加快速度的方法是通过向联盟添加范围来一次性更改。

注意:在Excel-VBA中获取速度时,屏幕更新应首先被禁用,最后一个要启用。如果你有特定于事件的触发器,还有其他事情可以像事件一样禁用。

答案 1 :(得分:0)

你可以使用类似的东西:

def test2(x):
    if x is not None:
        return True

if test2(False):
    print('False WILL cause execution')

if test2(True):
    print('True will cause execution')

if test2(np.array([])):
    print('An empty array will cause execution')

if test2(np.array([1, 2])):
    print('The test works for long arrays.')

它应该一直停在带数据的最后一行。