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

Performance 具有多个For循环的VBA代码运行速度非常慢,performance,vba,loops,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 Th

我的代码运行得很慢,是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

以下是几点建议:

  • 执行
    。选择
    会导致Excel更新UI,这很昂贵。尝试计算一次目标单元格/范围,并使用它调用PasteSpecial而不是Selection
  • 选择工作表(3)可以在循环之前完成,因为它不会改变
  • 如果(!)max.ONE dataArray元素与一个rngcell.Value匹配,则可以通过在结束IF之前使用Exit中止内部循环的其余部分,从而保存循环中无用的其余部分
您使用的是
范围(A:B)
,这无疑会降低您的代码速度。 Excel基本上会根据您的代码读取该范围内的每个单元格

那是200万个细胞


尝试使用类似于
Replace(range(“B”).End(Xldown).Address,“$B$”,”)的方法来限制B上的范围

可能更大,这样您就可以循环A列和B列中的每个单元格。您应该将循环限制为仅使用的范围。另外,看起来您可以通过自动筛选和复制可见行来消除所有循环。谢谢。关于自动筛选,我知道它可以筛选行,但它如何筛选列?