Excel Range.Find变得越来越慢
我有一个像这样的列的文件:
- ķ
- ķ
- ķ
- SND
- P
- P
- SND
- ķ
…
列的长度是例如20000.我使用以下C#代码沿此列移动:
while (true) { // Find SND dest_cells = ex_cells.Find("SND", dest_cells, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlWhole, Excel.XlSearchOrder.xlByColumns, Excel.XlSearchDirection.xlNext, false, false, false); // END? if (dest_cells.Row < row) return false; row = dest_cells.Row; // Find K dest_cells = ex_cells.Find("K", dest_cells, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlWhole, Excel.XlSearchOrder.xlByColumns, Excel.XlSearchDirection.xlNext, false, false, false); // END? if (dest_cells.Row < row) return false; row = dest_cells.Row; // Some operations /*there were some operations, but I commented them. So they don't influence on performance*/ }
每个后续search的持续时间在增加。 我没有测量时间。 但是只是为了解释,让它是:第一次查找需要0.1秒,秒0.2秒,十秒1秒,二十秒二十秒等等。
为什么? 我不明白
最快的方法取决于你想要做什么操作:但最好的办法是将数据列分配给一个对象数组并处理它(每次互操作调用Excel对象模型的开销都很高)。 有关各种方法的比较,请参阅http://fastexcel.wordpress.com/2011/10/26/match-vs-find-vs-variant-array-vba-performance-shootout/
当你循环时,你使用dest_cells
作为起点来寻找下一场比赛。 但是这个variables是在findK
和发现SND
之间共享的,而且这些variables的分布越多(在find匹配之后),代码就越需要在增加的区域中循环。 使用不同的variables,如matchK
和matchSnd