JavaScript Functions With in VBA: The Merger
Include a reference to ‘Microsoft Script Control 1.0’ as explained below, before proceeding with further JavaScript tricks in this page.- Goto Menu -> Tools -> Reference
- Search for “Microsoft Script Control 1.0’ in the listbox and enable it.
Coding Scripts inside VBA
As per Microsoft documentation, a script can be executed within a VBA in 4 different methods that is explained in detail in this page. In our examples we are only going to use ‘Run’ & ‘Eval’ methods.Sub JavaScript_in_VBA()
'Go to Menu -> Tool -> References -> Microsoft Script Control 1.0 & Enable by Clicking it
Dim jsObj As New ScriptControl
Dim InputValue1 As Integer, InputValue2 As Integer, Result As Integer
'Get Sample Parameters
InputValue1 = ThisWorkbook.Sheets(1).Cells(1, 1)
InputValue2 = ThisWorkbook.Sheets(1).Cells(1, 2)
'Define Scripting Language
jsObj.Language = "JScript"
With jsObj
'Add JavaScript Code to Script Control Object
.AddCode "function xProduct(a,b) {return (a*b);}"
'Execute Added Script & Get result
Result = .Run("xProduct", InputValue1, InputValue2)
'Result = .Eval("xProduct( 1, 2)")
End With
ThisWorkbook.Sheets(1).Cells(1, 3) = Result
End Sub
Sub VBScript_in_VBA()
Dim vbsObj As New ScriptControl
vbsObj.Language = "VBScript"
With vbsObj
.AddCode "function xGetDate() xGetDate = Date End Function"
MsgBox .Run("xGetDate")
MsgBox .Eval("xGetDate()")
End With
End Sub