2011-03-16 113 views
8

我有一个包含html单元格的Excel工作表。我如何批量将它们转换为纯文本?目前有这么多无用的标签和样式。我想从头开始编写它,但如果我可以获取纯文本,它将变得更加容易。将html转换为VBA中的纯文本

我可以编写一个脚本来将html转换为纯文本的PHP,所以如果你不能想到VBA中的解决方案,那么也许你可以告诉我如何将单元格数据传递到网站并检索数据。

回答

14

设置对“Microsoft HTML对象库”的引用。

Function HtmlToText(sHTML) As String 
    Dim oDoc As HTMLDocument 
    Set oDoc = New HTMLDocument 
    oDoc.body.innerHTML = sHTML 
    HtmlToText = oDoc.body.innerText 
End Function 

+0

这很好,但请注意,空白处已折叠。例如'

this[space][space][space]is
a[space]test
''出现这个[空间] isa [空间]测试'。 (对格式的抱歉;多余的空格不会在我输入时出现) – 2011-03-17 06:04:05

+0

在我看来,折叠空格将是“预期的行为”(除非元素文本使用css保留空格) – 2016-10-02 17:00:05

4

提取文本的一种非常简单的方法是按字符扫描HTML字符,并将尖括号外的字符累积到新字符串中。

Function StripTags(ByVal html As String) As String 
    Dim text As String 
    Dim accumulating As Boolean 
    Dim n As Integer 
    Dim c As String 

    text = "" 
    accumulating = True 

    n = 1 
    Do While n <= Len(html) 

     c = Mid(html, n, 1) 
     If c = "<" Then 
      accumulating = False 
     ElseIf c = ">" Then 
      accumulating = True 
     Else 
      If accumulating Then 
       text = text & c 
      End If 
     End If 

     n = n + 1 
    Loop 

    StripTags = text 
End Function 

这可能会留下很多无关的空白,但它会帮助删除标记。

3

Tim的解决方案是伟大的,工作很喜欢一个魅力。

我倒是愿意凑钱:使用此代码在运行时添加了“Microsoft HTML对象库”:

Set ID = ThisWorkbook.VBProject.References 
ID.AddFromGuid "{3050F1C5-98B5-11CF-BB82-00AA00BDCE0B}", 2, 5 

它工作在Windows XP和Windows 7

0

添的回答是优秀。但是,可以添加小调整以避免一个可预见的错误响应。

Function HtmlToText(sHTML) As String 
     Dim oDoc As HTMLDocument 

     If IsNull(sHTML) Then 
     HtmlToText = "" 
     Exit Function 
     End-If 

     Set oDoc = New HTMLDocument 
     oDoc.body.innerHTML = sHTML 
     HtmlToText = oDoc.body.innerText 
    End Function