MS Access VBA: Get/set Javascript Variable in Microsoft Web Browser ActiveX Control

By | February 5, 2011

In your MS Access application, if you are using Microsoft Web browser, we may have to interact with the Javascript variable inside the loaded page. There is no obvious method exists in the Web browser control but using the following trick you can get/set the Javascript variable in the webpage.

Quick Tip:

Add Javascript function to get/set the value of Javascript variable/ HTML element from/to the hidden field. Execute the function using VBA code with the help of DOM functions available in VBA. Please read further for the details or download the code.

Download Example:

Click here to download Example of getting/setting Javascript variable using VBA.

Pre-requisite:
You should own and be able to add Javascript functions and hidden field in the Web Page. If you do not own and not able to add Javascript function and hidden field in the web page, you can inject those using DOM manipulation functions in VBA.

  • hdnData – A hidden field
  • fnSetHiddenFieldFromVarOrHTML – Javascript function to set the hidden field hdnData from the Javascript variable or HTML element
  • fnSetVarOrHTMLFromHiddenField – Javascript function to set the Javascript variable or HTML element value from the hidden field hdnData
  • wbInstance – Name of the Web Browser ActiveX Control

Following code assumes that you have hardcoded/injected above mentioned Javascript functions and hidden field.

How to get value?

  • Execute the Javascript function using VBA
    wbInstance.Document.parentWindow.execScript("fnSetHiddenFieldFromVarOrHTML")
  • It will set the hidden field’s value from your interested javascript variable/HTML element’s value
  • Access hidden field using VBA code and get is value in VBA variable.
    Dim txtValue as String
    txtValue = wbInstance.Document.getElementById("hdnData").Value

How to set value?

  • Access hidden field using VBA code and set its value.
    Dim txtValue as String
    txtValue = "My Text"
    wbInstance.Document.getElementById("hdnData").Value = txtValue
  • Execute javascript function which will set the desired javascript variable/HTML element’s value from hidden field’s value.
    wbInstance.Document.parentWindow.execScript("fnSetVarOrHTMLFromHiddenField")

11 thoughts on “MS Access VBA: Get/set Javascript Variable in Microsoft Web Browser ActiveX Control

  1. Jeet

    To resolve this error: Run time error. Access Denied: -2147024891 (80070005)
    You need to run the Access exe with Admin privileges.
    This is a very common issue with browser automation.

Leave a Reply

Your email address will not be published. Required fields are marked *