0

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)">

How to send data to VBA? I have two problems:

  1. 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?

  2. How can I send the result of a JavaScript function to VBA?

PS.: I'm not searching how to start Javascript from VBA (Webbrowser.Document.parentwindow.execscript)

Thx

Martin

1

1 Answer 1

4

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.

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.

To find out how to fix your issues with local pages and js, Google "mark of the web".

In class module 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

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this solution! I just add that a separate class such as clsHtmlText is not technically needed, we can have it all inside the userform module, which also supports the declaration with WithEvents.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.