用于删除HTML代码的VB代码使~40k数据集的excel崩溃

时间:2016-08-01 19:04:46

标签: excel vba

这是我的VBA代码:

Sub RemoveTags()
Dim r As Range
Selection.NumberFormat = "@"  'set cells to text numberformat
With CreateObject("vbscript.regexp")
   .Pattern = "\<.*?\>"
   .Global = True
For Each r In Selection
    r.Value = .Replace(r.Value, "")
   Next r
End With
End Sub

它会从我的单元格中删除所有标记语言,但在运行~40k记录时会崩溃。我的代码有问题或我应该更改Excel设置吗?

1 个答案:

答案 0 :(得分:1)

我的猜测是Excel在尝试将文本写回单元格时崩溃了。 您可以尝试以下几种方法:

  • 使用.Value2而不是.Value来处理原始值。
  • 在文字前添加单引号。它不会出现,但会确保文本格式
  • 使用非后跟模式而不是非贪婪来确保处理换行符。
Sub RemoveTags()
    Dim values(), r As Long, c As Long, re As Object

    ' load the values in an array
    values = Selection.Value2

    ' create the regex
    Set re = CreateObject("vbscript.regexp")
    re.pattern = "<[^>]*>"
    re.Global = True

    ' remove the tags for each value
    For r = 1 To UBound(values, 1)
        For c = 1 To UBound(values, 2)
            values(r, c) = "'" & re.replace(values(r, c), vbNullString)
        Next
    Next

    ' write the values back to the sheet
    Selection.Value2 = values
End Sub