VBA 2010:关于编码实践的build议,以加速循环

我在脚本的一段中有一个循环,运行速度非常慢。 我希望得到一些改善这方面的build议。

我有8对数据集。 每一对都包含一个数组(一维,通常为400个string元素)和一个包含2000个string元素的列。 在每一对数据集中,我想检查数组的每个元素对列的每个元素进行匹配。 以下是我的方法的简化版本:

For i = 1 to 8 For j = 0 to 400 For k = 0 to 2000 If Cells(k,i) = myArray[1, then 2, then 3, etc.](j) then [action] next K next j next i 

通过以上操作,我循环遍历列A的前2000个单元400次,然后列B的前2000个单元400次,依此类推。 这似乎是非常多余的,大约有640万个单元格被检查,这是永久的。 我希望有一个更好的方法来做到这一点,有人启发我。

如果有必要的话,我可以告诉你实际的代码,并解释它正在做的所有事情,但是有点冗长。

编辑:这里是实际的代码。 它正在寻找也有一个合格的布尔值的模糊。 当这些条件得到满足时,它就取相应的整数值和行号。 它总结所有的整数值,并用它们的总和replace这些整数。 它为每个唯一的名称做了这个,然后(未显示),为剩余的7个数据集重复这一点。

  For i = 0 To j - 1 'starts with the first unique element and searches for dupes... v = 0 'initial qty value r = 0 'initial number of rows with dupes For k = 2 To WULastRow 'go though each cell in the first column If Cells(k, colPair + 2) = True And Cells(k, colPair).Text = uniqueNames(i) Then '...if one is found and the row's boolean is true... v = v + Cells(k, colPair + 1).Value '...sum it's qty with previous dupes qty's... r = r + 1 'increment number of dupes found ReDim Preserve rngMatch(r - 1) 'increase the size of the array that will hold the row numbers of the dupes. rngMatch(r - 1) = k '...and input dupe's row number to said array. End If Next k k = 0 'if 1 or more duplicate is found for the given unique item name is found... If r > 1 Then k = 0 For k = 0 To r - 1 Cells(rngMatch(k), colPair + 1).Value = v '...input the summed quantity in their qty cells... Next k End If Next i 'then regardless, move on to the name unique name and repeat this process. 

每次访问Cell(i,j)时都有很大的开销,

您需要通过使用单个语句将数据放入变体arry中,然后循环该数组,然后根据需要将其放回:这里是一些演示代码

 Option Base 1 dim vArr as variant varr=Range("A1").resize(Lastrow,LastCol).Value2 for j=1 to LastRow for k=1 to LastCol if vArr(j,k) .... then Varr(j,k)= ... next k next j Range("A1").resize(Lastrow,LastCol)=Varr 

你需要做的是实现某种types的variablessorting启发式,以matrix的顺序排列元素(从最低到最高等)。 下面是一个启动的例子:

如果我有一个数组a = [1,8,16] (按最小顺序排列),另一个数组b = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] (再次下令)我可以引入一个规则,每个search迭代发生在最后一次search的结束位置。 下面是我的意思是伪造的:

 index = 0 for i in a: for j in range(index, len(b)): if a == b: do something index = j 

这种有效的做法是,每当你匹配一个值时,你可以search一个迭代的越来越小的空间。 希望这是有道理的 – 在你的bmatrix中应用一个variablessorting的排名可能会很难。