慢VBA循环 – 从logging集粘贴

我正在使用循环而不是copyfromrecordset为两个列,打破copyfromrecordset出于某种未知的原因。 当我通过这个循环,需要2分钟做800行看起来非常缓慢。 Copyfromrecordset可以在不到20秒的时间内input多达10倍列的800行。 任何人都可以告诉是什么让循环这么慢?

Set rng = Activesheet.Range("P2") Row = 0 Do While Not Rs1.EOF For col = 0 To Rs1.Fields.Count - 1 rng.Offset(Row, col).Value = Rs1(col) Next col Row = Row + 1 Rs1.MoveNext Loop 

感谢@ThunderFrame,我能解决我的问题。 正如@ YowE3k所说,我的查询一次只做一件事。 所以我改变代码来使用.getrows。

  'Pasting data Headings then Values ArrRs1 = Rs1.GetRows For intColIndex = 0 To Rs1.Fields.Count - 1 Range("A1").Offset(0, intColIndex).Value = Rs1.Fields(intColIndex).Name Next Dim PasteArray As Variant ReDim PasteArray(1 To UBound(ArrRs1, 2), 0 To UBound(ArrRs1, 1)) For i = 1 To UBound(ArrRs1, 2) For j = 0 To UBound(ArrRs1, 1) PasteArray(i, j) = ArrRs1(j, i) Next Next 'This is pasting the data ActiveSheet.Range("A2").Resize(UBound(PasteArray, 1) + 1, UBound(PasteArray, 2) + 1) = PasteArray 

我没有很多copyfromrecordset的经验; 但是,如果每行都有屏幕更新,则可以closures屏幕,速度可能会有所提高。 这帮了我以前的“做直到”/“循环”。

我也将closures计算,尤其是在一个包含大量公式的庞大电子表格中。 如果Excel代码中有自动更新计算的位置,则重新计算工作簿可能会降低速度。

 application.screenupdating = false Application.Calculation = xlCalculationManual 'your code' application.screenupdating = true Application.Calculation = xlCalculationAutomatic