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.
See https://ramblings.mcpher.com/Home/excelquirks/snippets/scriptcontrol/arrays for more detail on this topic