【问题标题】:VBA HTML Object library not supporting all HTML tagsVBA HTML 对象库不支持所有 HTML 标签
【发布时间】:2020-06-12 16:40:29
【问题描述】:

使用 VBA 解析单元格行中的 HTML 时,某些标签会出现问题。

例如,如果我在 excel 单元格中有以下内容:

<div><section>hello</section></div>

然后我应用以下函数

Public Function mainclean(sourceText As String) As String

Dim DOC As New HTMLDocument
DOC.body.innerHTML = sourceText

mainclean = DOC.body.innerHTML
End Function

我得到的是以下内容:

<DIV>hello</SECTION></DIV>

节标签的开头被剥离。 很明显,标签部分没有被识别为 HTML 代码。

类似&lt;mycustomtag&gt;&lt;/mycustomtag&gt;这样的非html标签也会发生同样的情况

是否存在任何解决方法?

谢谢

【问题讨论】:

  • 可能是因为您将sourceText 声明为字符串。您将DOC 声明为HTMLDocument,但随后将其转换为带有DOC.body.innerHTML = sourceText 的字符串。不过只是猜测。
  • 我不认为HTMLDocument 实现了最新版本的 IE - 您可能会发现不支持最近/HTML5 标签。
  • 如果您想要 html 的内部文本,请将 innerHTML 更改为 innerText。您的 html 代码在 Excel 单元格中,因为?我从来没有听说过这是必要的。
  • @Zwenn - 很好 - 我完全错过了......
  • @TimWilliams 首先我也忽略了它并写了一些完全不同的东西。 String in, String out 让我分心了。

标签: html excel vba


【解决方案1】:

当使用HTMLDocument 时,默认documentMode 是IE5,这意味着最近/HTML5 标签会有一些问题。

如果需要,您可以使用 CreateObject("htmlfile") 创建相同类型的对象来解决此问题,但其行为似乎略有不同。

Sub Tester()

    Dim testHTML As String
    testHTML = "<div><section>hello</section></div>"

    Debug.Print mainclean(testHTML)

    Debug.Print mainclean2(testHTML)

End Sub

Public Function mainclean2(sourceText As String) As String
    Dim DOC 'As New HTMLDocument
    Set DOC = CreateObject("htmlfile")
    Debug.Print TypeName(DOC) '>>HTMLDocument
    Debug.Print "htmlfile Default doc mode", DOC.documentMode  '>>5
    DOC.Open "text/html"
    'next line switches document mode to 8 but commenting it out
    '  still gives the "correct" output with docMode 5 (??)
    DOC.write "<head><meta http-equiv=""X-UA-Compatible"" content=""IE=Edge""></head>"
    DOC.write "<body>" & sourceText & "</body>"
    DOC.Close
    Debug.Print "Fixed doc mode", DOC.documentMode '>>8
    mainclean2 = DOC.body.innerHTML                '>>  <DIV><SECTION>hello</SECTION></DIV>
End Function

Public Function mainclean(sourceText As String) As String
    Dim DOC As New HTMLDocument
    Debug.Print TypeName(DOC)                       '>>HTMLDocument
    Debug.Print "HTMLDocument Default doc mode", _
                               DOC.documentMode     '>> 5
    DOC.body.innerHTML = sourceText
    mainclean = DOC.body.innerHTML                  '>> <DIV>hello</SECTION></DIV>
End Function

相关: VBA doesn't read XMLHTTP request's response according to its tree structure

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多