如何将JavaScript结果从本地文件发送到VBA Webbrowser控件

时间:2017-05-15 19:21:06

标签: javascript vba ms-access

我在MS Access中使用标准的webbrowser控件。该控件显示本地HTML文件。现在,我想将数据从HTML发送到VBA。

<input type="text" onchange="foo(this.value)">

如何将数据发送到VBA?我有两个问题:

  1. 如果HTML文件是本地文件,我找不到启动JavaScript的解决方案。如果文件具有http URI,则可以使用alert(),但如果文件是本地文件则不可以。如何在本地文件中使用JavaScript?

  2. 如何将JavaScript函数的结果发送给VBA?

  3. PS。:我不是在搜索如何从VBA启动Javascript(Webbrowser.Document.parentwindow.execscript)

    THX

    马丁

1 个答案:

答案 0 :(得分:1)

您可以使用实现WithEvents的简单类来设置js-to-VBA通信,以将VBA引用连接到托管HTML页面中的元素。

当运行以下示例时,编辑然后单击HTML文本框(以便触发onchange事件)将通过链接到输入的类字段触发VBA消息框。

要了解如何解决本地网页和js的问题,Google“网络标记”。

在课程模块clsHtmlText中:

Option Explicit

Private WithEvents txt As MSHTML.HTMLInputElement

Public Sub SetText(el)
    Set txt = el
End Sub

Private Function txt_onchange() As Boolean
    MsgBox "changed: " & txt.value
End Function

在具有嵌入式浏览器控件的用户窗体中wb1

Option Explicit

Dim o As clsHtmlText '<< instance of our "withEvents" class

Private Sub UserForm_Activate()

    Dim el As MSHTML.HTMLInputElement
    With Me.wb1
        .Navigate "about:blank"
        WaitFor wb1
        .Document.Open "text/html"
        'or you can load a page from a URL/file
        'Note: local pages need "mark of the web" in the markup
        .Document.write "<html><input type='text' size=10 id='txtHere'></html>"
        .Document.Close
        WaitFor wb1

        Set el = .Document.getelementbyId("txtHere")

        Set o = New clsHtmlText
        o.SetText el '<< assign the textbox so we can monitor for change events

    End With

End Sub

'utility sub to ensure page is loaded and ready
Sub WaitFor(IE)
    Do While IE.ReadyState < 4 Or IE.Busy
        DoEvents
    Loop
End Sub