excel vba pass array to and from jscript

'VBA for passing arrays to and from JScript in the Script Control.

'JScript, running in the Microsoft Script Control, can be
'passed VBA safearrays... exactly the same as Internet Explorer can 
'be. But before JScript can do anything with the values in the 
'VBA foreign array, a new JScript array must be created based 
'on the VBA safearray:

vA = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
With CreateObject("ScriptControl")
    .Language = "JScript"
    .AddCode "function jsArray(v){return new VBArray(v).toArray()}"
    .AddCode "function sum(v){for(var a=jsArray(v),r=0,t=0;t<a.length;t++)r+=a[t];return r};"
    
  	MsgBox .Run("sum", vA)				'<--displays: 55
End With

'2D arrays and higher are converted to zero-based 1D JScript arrays
'by VBArray().toArray().

'Resource: 
'	https://developer.mozilla.org/en-US/docs/Web/JavaScript/Microsoft_Extensions/VBArray

'-------------------------------------------------------------------------------------------

'Attempting to return a JScript array from the Script Control 
'results in a comma delimited string passed to the VBA side.

'To return the actual array to VBA instead of a string, the array
'must first be converted to a VBA array. This can be done by
'utilizing the .items() property of the Scripting Dictionary:

vA = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
With CreateObject("ScriptControl")
    .Language = "JScript"
    .AddCode "function jsArray(v){return new VBArray(v).toArray()}"
	.AddCode "function vbArray(t){for(var r=new ActiveXObject('Scripting.Dictionary'),e=0;e<t.length;e++)r.add(e,t[e]);return r.items()}"
  	.AddCode "function roundTrip(v){return vbArray(jsArray(v))'}"
  
  	MsgBox UBound(.Run("roundTrip", vA))		'<--displays: 9  
End With

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source