Extending VBA with javaScript : the Array

In a post the other day i covered how to use the scriptcontrol to call javaScript directly from VBA. Considering that javaScript has plenty of useful methods for manipulating arrays and strings and so on that VBA doesn’t have, this could be an interesting approach to ‘extend VBA’. I thought i’d start with taking a look at some array methods. But I hit a couple of snags and found out some things too.

  • A javaScript array is not the same as a VBArray. It needs to be converted both to and from.
  • To pass back a VBArray to VBA, you actually created a scripting dictionary object and send that back. Strange but true.

The first test was to create a script that would sort an array using javaScript array.sort(). As it turns out, now I have the array format conversion code, any javaScript array method can be implemented. Here is the VBA code (you will need to add a reference to the scriptControl 1.0 object).

Public Sub testScriptControl()
    Dim sc As New ScriptControl, aList As Variant, _
        i As Long, sortedArray As Variant
    ' test data
    aList = Array("gamma", "alpha", "zeta", "delta")
    With sc
        .Language = "JScript"
        .AddCode _
            "function getArray(arrayIn) {" & _
                "var arr = new VBArray(arrayIn);" & _
                "var ja = arr.toArray();" & _
                "return ja;}" & _
            "function setArray(ja) {" & _
                "var dict = new ActiveXObject('Scripting.Dictionary');" & _
                "for (var i=0;i < ja.length; i++ )dict.add(i,ja[i]);" & _
                "return dict.items();}" & _
            "function sortArray(arrayIn){" & _
                "var ja = getArray(arrayIn);" & _
                "return setArray(ja.sort());}"
        sortedArray = .Run("sortArray", aList)
    End With
    For i = LBound(sortedArray) To UBound(sortedArray)
        Debug.Print sortedArray(i) & ":";
    Next i
End Sub

 

result is alpha:delta:gamma:zeta:

watch this space and see the ramblings site for more stuff like this.

About brucemcp 225 Articles
I am a Google Developer Expert and decided to investigate Google Apps Script in my spare time. The more I investigated the more content I created so this site is extremely rich. Now, in 2019, a lot of things have disappeared or don’t work anymore due to Google having retired some stuff. I am however leaving things as is and where I came across some deprecated stuff, I have indicated it. I decided to write a book about it and to also create videos to teach developers who want to learn Google Apps Script. If you find the material contained in this site useful, you can support me by buying my books and or videos.