0

I have an issue(using VBA with Excel 07) where my code is slowing down when running through a long loop. I'm 95% sure this slowdown is caused because I'm writing to many different cells individually instead of as one block.

However, I'm not sure how to fix this as most of the cells I need to write to are non-contiguous and non-consecutive. Take the below for example:

    ActiveSheet.Range("b2").Value = Sheet6.Cells(regionMembers(i), 2)
    ActiveSheet.Range("j4").Value = Sheet6.Cells(regionMembers(i), 4)
    ActiveSheet.Range("e6").Value = Sheet6.Cells(regionMembers(i), 5)
    ActiveSheet.Range("d22").Value = Sheet6.Cells(regionMembers(i), 6)
    ActiveSheet.Range("d23").Value = Sheet6.Cells(regionMembers(i), 7)

This is a small section of the cells that need to be written to (the total is around 150 per loop and the loop is the extent of the array regionMembers(), where region members can hold up to 40-50 values).

Is there any way for me to write the values on sheet6 to a variant array and then paste it to the active sheet in one block?

I know for a range like "A1:A100", you can presumably set a range to ("A1", "A100"), then store all the values you want pasted in an array then do something like:

myRange.Value = myArray

But I cannot figure out how to do this when the range is non-consecutive.

Any help would be appreciated.

4

1 回答 1

2

这本身不应该是一个问题,但您可能需要稍微优化该过程。我会尝试在宏期间关闭计算(如果逻辑允许):

Application.Calculation = xlCalculationManual

然后再重新打开它

Application.Calculation = xlCalculationAutomatic

您不能将非连续范围分配给值:myRange.Value = myArray仅适用于连续范围。(底层变体 myArray 不支持非连续性)。

于 2013-05-28T14:31:50.073 回答