VBA 代码编辑 HTML 文件而不会丢失 <head>...</head> 信息

问题描述

我正在尝试创建一个 excel 宏来编辑我磁盘上的 html 文件。我正在使用这样的东西:

Sub changeImg()

    Dim dom As HTMLDocument
    Dim img As Object
    Dim src As String

    Set dom = CreateObject("htmlFile")

    Open "C:\temp\test.html" For Input As #1
        src = Input$(LOF(1),1)
    Close #1

    dom.body.innerHTML = src

    Set img = dom.getelementsbytagname("img")(0)

    img.src = "..."

    Open "C:\temp\test.html" For Output As #1
        Print #1,dom.DocumentElement.outerHTML
    Close #1


End Sub

问题是我丢失了起始文件中 中的所有信息。我无法弄清楚如何保留所有的 html 代码,并且只使用 getElementById 替换我想要的内容。任何帮助或方向表示赞赏。谢谢。

解决方法

尝试这样的事情:

Dim doc
Set doc = CreateObject("htmlfile")

doc.Open "text/html"
'next line could use content read from a file...
doc.write "<html><head><title>The title</title></head><body>The body</body></html>"
doc.Close

Debug.Print doc.Title
Debug.Print doc.body.innerText

doc.Title = "New Title here"
doc.body.innerHTML = "New body here"

Debug.Print doc.Title
Debug.Print doc.body.innerText

Debug.Print doc.DocumentElement.outerHTML 'or write to file...
     
,

这对我有用。

Dim doc
Set doc = CreateObject("htmlfile")
Dim src As String

doc.Open 'next line could use content read from a file...

Open "C:\new.html" For Input As #1 'this is my line to read from a file.
src = Input$(LOF(1),1)
Close #1


doc.write src
doc.Close

Debug.Print doc.Title
Debug.Print doc.body.innerText

doc.Title = "New Title here"
doc.body.innerHTML = "New body here"


Debug.Print doc.Title
Debug.Print doc.body.innerText

Debug.Print doc.DocumentElement.outerHTML 'or write to file...


Open "C:\new.html" For Output As #1 'this is my line to write to a file
Print #1,doc.DocumentElement.outerHTML
Close #1

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...