问题描述
我在 MS Access 中使用标准的 webbrowser 控件.该控件显示本地 HTML 文件.现在,我想将数据从 HTML 发送到 VBA.
I'm using the standard webbrowser control in MS Access. The control shows a local HTML file. Now, I want to send data from HTML to VBA.
<input type="text" onchange="foo(this.value)">
如何向VBA发送数据?我有两个问题:
How to send data to VBA? I have two problems:
如果 HTML 文件是本地的,我根本找不到启动 JavaScript 的解决方案.如果文件有一个 http URI,例如
alert()
是可能的,但如果文件是本地的则不行.如何在本地文件中使用 JavaScript?
If the HTML file is local, I found no solution to start JavaScript at all. If the file has an http URI,
alert()
for example is possible, but not if the file is local. How can I use JavaScript in a local file?
如何将 JavaScript 函数的结果发送到 VBA?
How can I send the result of a JavaScript function to VBA?
PS.: 我不是在搜索如何从 VBA (Webbrowser.Document.parentwindow.execscript) 启动 Javascript
PS.: I'm not searching how to start Javascript from VBA (Webbrowser.Document.parentwindow.execscript)
谢谢
马丁
推荐答案
您可以使用实现 WithEvents 的简单类来设置 js 到 VBA 的通信,以将 VBA 引用连接到您托管的 HTML 页面中的元素.
You can set up js-to-VBA communication using simple classes implementing WithEvents to hook up VBA references to elements in your hosted HTML page.
当下面的示例运行时,编辑然后单击 HTML 文本框(因此触发 onchange
事件)将通过链接到输入的类字段触发 VBA 消息框.
When the example below is run, editing and then clicking out of the HTML textbox (so firing the onchange
event) will trigger a VBA messagebox via the class field linked to the input.
要了解如何解决本地网页和 js 的问题,请使用 Google网络标记".
To find out how to fix your issues with local pages and js, Google "mark of the web".
在类模块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
:
In a UserForm with an embedded browser control 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
这篇关于如何将 JavaScript 结果从本地文件发送到 VBA Webbrowser 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!