替换为用单元格替换函数单元格-VBA



我目前有几十列,每列有数百行。我正在调用的一个subs在从web上托管的XML中输入单元格的数据后,会去修改单元格的数据。当前的方法是有效的,但它往往会变得有点慢,因为它是逐单元进行更改的。这是我的代码:

Private Sub fixEnt(listCol As ListColumn) 'fixes the HTML/XML entities
Dim rng As Range
On Error Resume Next
Set rng = listCol.DataBodyRange.SpecialCells(xlCellTypeConstants)
On Error GoTo 0
If Not rng Is Nothing Then
For Each areaItem In rng.Areas 'iterate over the arrays in the Areas array
For Each cell In areaItem 'iterate over the values in the Item array
cell.Value = decodeEnt(cell.Value)
Next
Next
End If
End Sub

它调用decodeEnt:

Private Function decodeEnt(cellVal As String) As String
Dim tempStr$ 'holds new value after replace
tempStr = Replace(cellVal, """, Chr(34)) 'Chr(34) is a "
tempStr = Replace(tempStr, "'", "'")
tempStr = Replace(tempStr, "&", "&")
tempStr = Replace(tempStr, "&#60;", "<")
tempStr = Replace(tempStr, "&#62;", ">")
tempStr = Replace(tempStr, "&#160;", " ")
tempStr = Replace(tempStr, "&#35;", "#")
tempStr = Replace(tempStr, "&nbsp;", " ")
tempStr = Replace(tempStr, "&lt;", "<")
tempStr = Replace(tempStr, "&gt;", ">")
tempStr = Replace(tempStr, "&quot;", Chr(34))
tempStr = Replace(tempStr, "&apos;", "'")
tempStr = Replace(tempStr, "&amp;", "&")
tempStr = Replace(tempStr, "&ndash;", "–")
tempStr = Replace(tempStr, "&#252;", "ü")
tempStr = Replace(tempStr, "&deg;", "°")
tempStr = Replace(tempStr, "&auml;", "ä")
tempStr = Replace(tempStr, "&uuml;", "ü")
tempStr = Replace(tempStr, "&rsquo;", "’")
decodeEnt = tempStr 'Return modified string
End Function

有没有更快的方法来执行那个操作?在rng中同时修改数据的东西。区域阵列?速度是这个项目的关键,但我对此没有任何想法。

感谢

编辑:进一步澄清项目。它从另一个工具的API中导入XML文件,并将其保存到Excel中的表中。我还有其他代码刷新连接,附加XML中的所有数据(新的和旧的)。一旦刷新过程完成,它就开始修改数据,包括固定单元格中的HTML/XML实体和固定日期格式。修改完成后,它会删除重复的行(因为在刷新时无法只添加新数据)。

希望这能消除任何困惑。

我怀疑以下操作会更快(同时处理所有单元格):

Sub test()
Dim replaceThis()
Dim withThis()
replaceThis = Array("&lt;", "&gt;") ' etc
withThis = Array("<", ">") ' etc
Application.ScreenUpdating = False
For i = LBound(replaceThis) To UBound(replaceThis)
'MsgBox "replacing " & replaceThis(i) & " with " & withThis(i)
Range("A1:A5").Replace What:=replaceThis(i), Replacement:=withThis(i), _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False
Next i
Application.ScreenUpdating = True
End Sub

请注意,您需要创建一个包含所有替换的数组,我对范围进行了硬编码:您需要创建该变量。但看到你的代码,我想你可以从这里弄清楚。

有一个范围的替换函数,它可能更快。

一般性能提示(尤其是屏幕更新、计算和"在一次操作中读取/写入大块单元格"):

http://blogs.office.com/2009/03/12/excel-vba-performance-coding-best-practices/

(根据我的经验,主要有助于停用应用程序。屏幕更新,停用应用程序,在一次操作中计算或读取/写入大块单元格)

最新更新