VBA-将创建的HTML元素追加到HEAD元素的问题

时间:2019-01-06 17:52:14

标签: javascript excel vba userform

我正在尝试在UserForm Webbrowser控件和表单本身之间实现javascript“桥梁”。我觉得我现在快到了,请参阅下文。但是我似乎无法将创建的脚本附加到加载到Web浏览器中的文档的标题中。错误是“ head.appendChild(scriptEl)”行上的“需要对象”。我用msgbox显示了显示所有HTML的head.innerHTML,还有scriptEl.innerHTML具有完整的script元素,所以不确定为什么会发生此错误。

Private Sub CommandButton2_Click()

Dim head As HTMLGenericElement
Dim scriptEl As HTMLScriptElement
Dim element As HTMLScriptElement



Set head = WebBrowser1.Document.GetElementsByTagName("head")(0)
Set scriptEl = WebBrowser1.Document.createElement("script")

    scriptEl.Text = "function sayHello() { alert('hello') }"
    head.appendChild (scriptEl)
    WebBrowser1.Document.InvokeScript ("sayHello")

End Sub

1 个答案:

答案 0 :(得分:1)

我建议使用以下代码:

' Add references
' Microsoft Internet Controls
' Microsoft HTML Object Library

Private Sub UserForm_Initialize()

    With WebBrowser1
        .Navigate "about:blank"
        Do Until .ReadyState = READYSTATE_COMPLETE And Not .Busy: DoEvents: Loop
        .Document.parentWindow.execScript "function sayHello() { alert('hello') }"
    End With

End Sub

Private Sub CommandButton2_Click()

    WebBrowser1.Document.parentWindow.execScript "sayHello();"

End Sub