【问题标题】:How to sending JavaScript results from local file to VBA Webbrowser control如何将 JavaScript 结果从本地文件发送到 VBA Webbrowser 控件
【发布时间】:2017-05-15 19:21:06
【问题描述】:
我在 MS Access 中使用标准的网络浏览器控件。该控件显示一个本地 HTML 文件。现在,我想将数据从 HTML 发送到 VBA。
<input type="text" onchange="foo(this.value)">
如何向 VBA 发送数据?我有两个问题:
如果 HTML 文件是本地文件,我根本找不到启动 JavaScript 的解决方案。如果文件有一个 http URI,例如alert() 是可能的,但如果文件是本地的,则不是。如何在本地文件中使用 JavaScript?
如何将 JavaScript 函数的结果发送到 VBA?
PS.:我不是在搜索如何从 VBA 启动 Javascript (Webbrowser.Document.parentwindow.execscript)
谢谢
马丁
【问题讨论】:
标签:
javascript
vba
ms-access
【解决方案1】:
您可以使用实现 WithEvents 的简单类来设置 js 到 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