我正在尝试在VBA中编辑HTML,并有以下代码片段:
Sub Test()
Dim filePath As String
Dim spanElement As HTMLSpanElement
' Create an HTML document object
Dim htmlDoc As Object
Set htmlDoc = CreateObject("htmlfile")
' File path to the local HTML file
filePath = "C:\Users\Public\somedoc.htm"
' Load the HTML file into the HTML document
With CreateObject("Scripting.FileSystemObject").OpenTextFile(filePath)
htmlDoc.write
.ReadAll
.Close
End With
' Find the <span> element by its ID
Set spanElement = htmlDoc.getElementById("firstname")
' Change the text within the <span> element
If Not spanElement Is Nothing Then
spanElement.innerText = "New Text"
Else
MsgBox "Span element not found."
End If
End Sub
html测试文件:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Template</h1>
<p>This is a blank template for a web page.</p>
<p class=MsoNormal>Good Morning<span id="firstname"></span></p>
</body>
</html>
但在这条线上
Set spanElement = htmlDoc.getElementById("firstname")
我得到一个运行时错误`Run time error 424-Object Required。
我做错了什么?