8

I believe I need to call a javascript method instead of trying to fire buttons. I have tried the following examples and I think my problem is that I don't know which parts of the code I should use..Click button or execute JavaScript function with VBA and this http://www.vbaexpress.com/forum/showthread.php?9690-Solved-call-a-javascript-function and http://www.vbforums.com/showthread.php?650771-RESOLVED-How-to-Call-a-JavaScript-function-From-Visual-Basic-6-WITH-wanted-parameters

I can't post a link because it requires a login to access it... Please let me know if you need a larger sample of the code to make sense of my question.

I believe I need a function that references "Export as CSV" but I am not sure which function to call and which parts of function to include in the call... The following is from catalog.js

  function()
  {var a=window.Ext4||window.Ext;a.define    ("Rally.alm.ui.page.plugins.PageToolFactory",{singleton:true,mixins:    {messageable:Rally.Messageable},PRINT:"PRINT",IMPORT:"IMPORT",EXPORT:"EXPORT",ge    t:function(c,b)
{var d=[];
if(this._shouldHaveRowAction(this.PRINT,c))
{
if(b.getPlugin("printplugin"))
{
d.push({text:"Print...",handler:b.getPlugin("printplugin").print,cls:"page-    tools",scope:b.getPlugin("printplugin"),addInteractionClass:true})}}
if(this._shouldHaveRowAction(this.IMPORT,c))
{
if(b.getPlugin("printplugin"))
{
d.push({text:"Import User Stories...",handler:a.emptyFn})}}
if(this._shouldHaveRowAction(this.EXPORT,c))
 {
    if(b.getPlugin("printplugin"))
                  {
                              d.push({text:"Export as  CSV",handler:a.emptyFn})}}                                                                return d}

This next sample is from yui.js...

 (function()
 {
 RALLY.ui.menu.AvailablePageTools=Ext.extend(Object, {constructor:function()
 {
 this.PRINT={text:'Print...',slug:'print'};
 this.EMAIL={text:'Email...',slug:'email'};
 this.SAVE={text:'Save...',slug:'save'};
 this.CSV_IMPORT={text:'Import User Stories...',slug:'csvimport'};
 this.CSV_IMPORT_PORTFOLIO_ITEM={text:'Import Portfolio    Items...',slug:'csvimport'};
 this.CSV_EXPORT={text:'Export as CSV',slug:'csvexport'};
 this.PDF_EXPORT={text:'Export as PDF',slug:'pdfexport'};

I have tried these options in my vba script..

Dim objIE As SHDocVw.InternetExplorer 'microsoft internet controls   (shdocvw.dll)
Dim htmlDoc As MSHTML.HTMLDocument 'Microsoft HTML Object Library
Dim htmlInput As MSHTML.HTMLInputElement
Dim htmlColl As MSHTML.IHTMLElementCollection
Dim CurrentWindow As HTMLWindowProxy




'Set objIE = Nothing
Set objIE = New SHDocVw.InternetExplorer

ThisWorkbook.Worksheets("Sheet1").Activate


With objIE

   .navigate "website"
    .Visible = 1
    Do While .readyState <> 4: DoEvents: Loop
        Application.Wait (Now + TimeValue("0:00:02"))

    Set htmlDoc = .document

    objIE.document.all.Item
        'Set CurrentWindow = objIE.htmlDoc.parentWindow
        'no error no export
        'Call objIE.document.parentWindow.execScript("_exportHandler:Function()", "JavaScript")

         'no error no export
        'Call objIE.document.parentWindow.execScript("_getExportItems:Function()", "JavaScript")

        'RUN TIME ERROR could not complete the operation due to error 80020101 (error while evaluating js)
        'Call objIE.document.parentWindow.execScript("_a.define()", "JavaScript")

        'run time error the object invoked has disconnected from its clients,
        'RUN TIME ERROR could not complete the operation due to error 80020101 (error while evaluating js)
        'Call objIE.document.parentWindow.execScript("_b.push()", "JavaScript")

        'run time error the object invoked has disconnected from its clients,
        'RUN TIME ERROR could not complete the operation due to error 80020101 (error while evaluating js)
         'Call objIE.document.parentWindow.execScript("handler:function(){window.location=Rally.ui.grid.GridExport.buildCsvExportUrl(this.gridboard.getGridOrBoard())}", "JavaScript")

        'Call objIE.document.parentWindow.execScript("b.push()", "JavaScript")

        'Call objIE.document.parentWindow.execScript("c.push()", "JavaScript")

        'RUN TIME ERROR could not complete the operation due to error 80020101 (error while evaluating js)
        'Call objIE.document.parentWindow.execScript("this.CSV_Export()", "JavaScript")

        'error the remote server machine does not exist or is unavailable
        'Call objIE.document.parentWindow.execScript("constructor:function()", "JavaScript")

        'Call objIE.document.parentWindow.execScript("constructor:function()", "JavaScript")

        'object
        Call CurrentWindow.execScript("d.push({text:CHR(34)Export as CSV CHR(34),handler:a.emptyFn})")

        'ofile.SaveAs scrapeRally:=ofile.Name
       'ofile.Close savechanges:=False

        'objIE.Quit
        Set objIE = Nothing

 End With

 End Sub

I am trying to run this from VBA so I couldnt use var...

Dim getFunction = "get:function (_shouldhaverowaction(this.export,C)),(b.getPlugin(chr(34)printplugin chr(34)))" 

Dim exportNow 
eval ("exportNow = new" + getFunction + ";") 

And I also tried

Call objIE.HTMLDocument.eval("get:function (_shouldhaverowaction(this.export,C)),(b.getPlugin( chr(34) printplugin chr(34)))", "JavaScript") 

I got "The object doesnt support this property or method" error when I tried to run it.

Any suggestions would be really great.

I just came across another function that could be the one I want but I still don't know what part of it I should use to call. I tried to call just _getExportItems:function() but I get RUN TIME ERROR could not complete the operation due to error 80020101 (error while evaluating js)

 _getExportItems:function(){
 var b=[];
 if(this.enableCsvExport){
b.push({
text:"Export to CSV...",
handler:function(){
window.location=Rally.ui.grid.GridExport.buildCsvExportUrl   (this.gridboard.getGridOrBoard())},scope:this})}
2
  • execScript is no longer supported. Starting with Internet Explorer 11, use eval. Commented Jul 20, 2015 at 19:08
  • Hi Dee I followed your link and tried these two things.. I am trying to run this from VBA so I couldnt use var... 'Dim getFunction = "get:function (_shouldhaverowaction(this.export,C)),(b.getPlugin(chr(34)printplugin chr(34)))" 'Dim exportNow 'eval ("exportNow = new" + getFunction + ";") AND I ALSO TRIED Call objIE.HTMLDocument.eval("get:function (_shouldhaverowaction(this.export,C)),(b.getPlugin( chr(34) printplugin chr(34)))", "JavaScript") I GOT THE OBJECT DOESNT SUPPORT THIS PROPERTY OR METHOD ERROR.. Commented Jul 20, 2015 at 20:59

1 Answer 1

4

Here simple example which uses execScript method of the window object. It calls a global functions named myFunc and myFuncWithParams. Code was tested with IE 11.

Option Explicit

Private Const Url As String = "c:\Temp\evalExample.html"

Public Sub Test()
    Dim objIE As SHDocVw.InternetExplorer
    Dim currentWindow As HTMLWindowProxy

    Set objIE = New SHDocVw.InternetExplorer
    objIE.navigate Url
    objIE.Visible = 1

    Do While objIE.readyState <> 4
        DoEvents
    Loop

    Set currentWindow = objIE.document.parentWindow

    ' Here the function without parameters is called.
    currentWindow.execScript code:="myFunc()"

    ' Here the function with parameters is called.
    ' First parameter is numeric, then string, then boolean and finally object.
    ' The object has three properties, numeric, string and array.
    currentWindow.execScript code:="myFuncWithParams(123, 'Some text', true, { property1: 555, property2: 'hi there from object', property3: [111,222,333] })"

    ' And here function which receives parameters and returns value.
    ' The return value is then available through hidden property of document named 'Script'.
    ' Thanks to this answer: https://stackoverflow.com/questions/9005914/retrieve-return-value-of-a-javascript-function-in-the-webbrowser-control-in-vb6
    currentWindow.execScript code:="func = function(){return myFuncReturns(2,3);}; retVal = func();"
    Dim result As Long
    result = objIE.document.Script.retVal
    Debug.Print result ' for 2 and 3 prints 5

    objIE.Quit
    Set objIE = Nothing
 End Sub

evalExample.html

<!-- saved from url=(0016)http://localhost -->
<html>
<head>
    <script type="text/javascript">
        function myFunc() {
            var date = new Date();
            alert("Hi from my parameter-less 'myFunc'. Day of the month: " + date.getDate());
        }

        function myFuncWithParams(a, b, c, d) {
            var number = a + 100,
                text = b + " from my func2",
                bool = !c,
                obj = d;

            var alertText = "\nNumber = '" + number + "'" +
                            "\nText = '" + text + "'" +
                            "\nBoolean = '" + bool + "'" +
                            "\nObject.property1 = '" + obj.property1 + "'" +
                            "\nObject.property2 = '" + obj.property2 + "'" +
                            "\nObject.property3.lenght = '" + obj.property3.length + "'" + 
                            "\nObject.property3[2] = '" + obj.property3[2] + "'";

            alert("Hi from my 'myFunc2' with parameters.\n" + alertText);
        }

        function myFuncReturns(a, b) {
            return a + b;
        }
    </script>
</head>
<body>
    <div>eval test</div>
</body>
</html>
Sign up to request clarification or add additional context in comments.

6 Comments

Hi Dee thank you for your help! I am in over my head for sure, please excuse the dumb questions... For the second code snippet, is that supposed to represent my website sourcecode I am referring to? Or am I supposed to incorporate that somewhere in my vba script?
Dee the site I am trying to code vba against has several js files. Should I refer to one of them specifically to call the function I need? Thank you!
This is just an example (very basic one) how to call a java-script function with the execScript method. In your case you have to find the name of the java-script function you need to execute and use this name instead of 'myFunc()'.
I have plugged in all the functions I thought that might be what I want but I still haven't been successful... In your example, you call the function without parameters included. Can you include/should you include the parameters when you call js function from vba script?
I have edited the answer and added a second function with parameters and how to call this function from VBA. Maybe Getting Started with the F12 Developer Tools might help you to find the right java-script function.
|

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.