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