更快的执行循环的方法

时间:2016-12-07 07:13:45

标签: excel-vba vba excel

我是VBA的新手,需要帮助找出更快的方法来执行我的代码。这是我正在使用的代码:

Sub loop()
For i = 1 To 100000
check_cell = Sheets("Sheet1").Range("I" & i)
  For j = 1 To 14430
    text_to_check = Sheets("Sheet2").Range("D" & j)
    text_to_fill = Sheets("Sheet2").Range("E" & j)
    If InStr(check_cell, text_to_check) Then
      Sheets("Sheet1").Range("J" & i).Value = text_to_fill
    End If
  Next j
Next i
End Sub

我知道我通过循环运行系统1,443,000,000次使用非常残酷的方式。任何有关缩短这一点的帮助将不胜感激。感谢。

编辑:根据建议,我尝试使用变体的新代码,但似乎没有发生任何事情。你能告诉我在这里做错了什么吗?感谢

Sub loop_2()
    Dim varray_1 As Variant
    Dim varray_2 As Variant
    Dim i As Long
    Dim j As Long
    varray_1 = Sheets("L1").Range("I2:I39997").Value
    varray_2 = Sheets("Sheet2").Range("G1:G14394").Value
    For i = UBound(varray_1, 1) To LBound(varray_1, 1) Step -1
        For j = UBound(varray_2, 1) To LBound(varray_2, 1) Step -1
            If varray_1(i, 1) = varray_2(j, 1) Then
                Sheets("L1").Range("L" & i).Value = Sheets("Sheet2").Range("H" & j).Value
            End If
        Next j
    Next i
End Sub

2 个答案:

答案 0 :(得分:2)

我还没有测试过这段代码,但至少应该知道如何将值放入数组,处理所有内容" in-memory",然后将结果写出来。

Sub loop()
    Dim i As Long
    Dim j As Long
    Dim check_cell() As Variant
    Dim result() As Variant
    Dim text_to_check() As Variant
    Dim text_to_fill() As Variant

    check_cell = Sheets("Sheet1").Range("I1:I100000").Value
    result = Sheets("Sheet1").Range("J1:J100000").Value
    text_to_check = Sheets("Sheet2").Range("D1:D14430").Value
    text_to_fill = Sheets("Sheet2").Range("E1:E14430").Value
    For i = 1 To 100000
        For j = 1 To 14430
            If InStr(check_cell(i, 1), text_to_check(j, 1)) Then
                 result(i, 1) = text_to_fill(j, 1)
                 If i = 1 Then
                     Debug.Print "check_cell=" & check_cell(i, 1)
                     Debug.Print "j=" & j
                     Debug.Print "text_to_check=" & text_to_check(j, 1)
                     Debug.Print "text_to_fill=" & text_to_fill(j, 1)
                 End If
                 ' exit as soon as first match is made
                 Exit For
            End If
        Next j
    Next i
    Sheets("Sheet1").Range("J1:J100000").Value = result
End Sub

答案 1 :(得分:0)

此处的最高费用是使用InStr(),但您还应该:

  • 声明您的变量,Variant更慢
  • 包裹你的循环
    With Sheets("Sheet1")
       ...
    End With
    
  • 将单元格寻址更改为.Cell(10, i)而不是.Range("D" & j)

我的测试表明它的运行速度提高了50%,请注意我将所有单元格都清空,因此InStr()成本相对较低。