VB源代码

关于提高外部调用遍历替换Excel数据速度的方法

2018-07-31  本文已影响0人  因思道客

最近在做一个批量替换程序,之前使用VBA在Excel内部调用任何方法速度都很快(例如方法1),但是外部调用Excel对象次数多了,程序就运行很慢了。想了以下4种方法实现,最终选用了方法4。先将数据统一读取到数组中,然后遍历内存中的数组,再调用Range对象进行替换,这样对于Excel对象的调用仅2次即可完成一次替换。

实际上方法2替换速度应该最快的,仅一次对象调用就把一个工作表的数据都替换了。但是无返回值。是否替换了?替换了哪些都不清楚。

第三种方法是先使用Find或FindNext方法找到值,然后再替换,判断复杂,但也算是一种折中的方法。

方法1:遍历所有单元格,速度很慢

For Each Rng In sht.UsedRange

str = Rng.Value

  If InStr(str, OldStr(j)) Then

    Rng.Value = Replace(str, OldStr(j), NewStr(j))

    xlsOldStrCount(j) = xlsOldStrCount(j) + 1

  End If

Next

方法2:使用Excel内置方法直接替换,速度很快,但不知道替换了哪些

appExcel.DisplayAlerts = False

Call sht.UsedrRang.Replace(What:=OldStr(j), Replacement:=NewStr(j))

appExcel.DisplayAlerts = True

方法3:先查找,后替换,暂时有问题

查找替换前文本

Rng = sht.Cells(1, 1)

Rng = sht.Cells.Find(What:=OldStr(j))

If Not Rng Is Nothing Then

rng1 = Rng.Address

Do

If Rng.Address = rng1 Then

Exit Do

End If

Rng.Value = Replace(Rng.Value, OldStr(j), NewStr(j))

xlsOldStrCount(j) = xlsOldStrCount(j) + 1

Rng = sht.Cells.FindNext(After:=Rng)

If Rng Is Nothing Then

Exit Do

ElseIf Rng.Address = rng1 Then

Exit Do

End If

Loop While (Not Rng Is Nothing)

End If

方法4:将数据读入数组Arr,再遍历数组,兼顾速度和明确替换了哪些数据。

                                Arr = sht.Range(sht.Cells(1, 1), sht.UsedRange.SpecialCells(11)).Value

For k = 1 To UBound(Arr, 1)

For n = 1 To UBound(Arr, 2)

If InStr(CStr(Arr(k, n)), OldStr(j)) Then

sht.cells(k, n) = Replace(CStr(Arr(k, n), OldStr(j), NewStr(j))

xlsOldStrCount(j) = xlsOldStrCount(j) + 1

End If

Next

Next k

上一篇 下一篇

猜你喜欢

热点阅读