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

VBA code to edit HTML file without losing <head>...</head> information

我正在尝试创建一个 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

问题是我丢失了起始文件中 <\head> 中的所有信息。我无法弄清楚如何保留所有 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