具有多个For循环的VBA代码运行速度非常慢

时间:2015-01-26 13:13:29

标签: performance vba loops

我的代码运行速度很慢,是2 For循环导致吗?

谢谢

    For x = LBound(dataArray) To UBound(dataArray) 'define start and end of array, lower bound to upper bound
        For Each rngcell In Range("A:B") 'lookup each cell in row 1
            If dataArray(x) = rngcell.Value Then ' if cells in header row match with values in array
                rngcell.EntireColumn.Copy ' then copy whole column of data for that parameter
                Sheets(3).Select ' select sheet to paste data
                Range("A:B").End(xlUp).Offset(rowOffset:=0, columnOffset:=x).Select 'select area to paste, paste in next column - no. x
                Selection.PasteSpecial xlPasteValues ' paste
            End If
        Next rngcell ' next header row cell
    Next x
End Sub

2 个答案:

答案 0 :(得分:1)

只是一些建议:

  • 执行.Select会导致Excel更新UI,这很昂贵。尝试计算目标单元格/范围ONCE并使用它来调用PasteSpecial而不是Selection。
  • 选择Sheet(3)可以在循环之前完成,因为它没有改变。
  • IF(!)max。 ONE dataArray Element匹配ONE rngcell.Value,你可以在End If之前使用Exit For中止内部循环的其余部分,保存循环中无用的其余部分。

答案 1 :(得分:1)

您正在使用Range(A:B),这肯定会降低您的代码速度。 Excel将根据您的代码基本读取该范围内的每个单元格。

那200万个细胞。

尝试使用类似Replace(Range("B").End(Xldown).Address,"$B$","")的内容来限制B的范围。

相关问题