代码之家  ›  专栏  ›  技术社区  ›  Al Grant

在VBA中编辑HTML

  •  0
  • Al Grant  · 技术社区  · 1 年前

    我正在尝试在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。

    我做错了什么?

    1 回复  |  直到 1 年前
        1
  •  1
  •   TinMan    1 年前

    HTMLDocument中未写入任何内容。进行以下更改:

    htmlDoc.write .ReadAll