2016-08-01 70 views
2

這是我的VBA代碼:VB代碼以刪除HTML代碼總是崩潰Excel的〜40K的數據集

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設置?

+6

[不使用正則表達式來解析HTML(或對其進行處理)](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self -contained標籤/ 1732454#1732454)。將HTML加載到「HTMLFile」對象並返回文檔對象的'.innerText'可能會更好。 –

+0

嘗試'Selection.Replace「<*>」,「」'改爲 – Slai

回答

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