Episoft

FAQ: VBA Support

Using Mathematica Link for Excel 3, you can call Mathematica from the Excel VBA environment. The syntax of the Mathematica VBA function has changed since version 2. In version 3, the API is much cleaner. It is now much easier to do things such as return arrays.

We are updating the VBA-side documentation which should eventually make it into the manual. Until then, here are a few examples to give you the idea of how to do it.

result = Application.Run("Mathematica", Array("Plus", 2, 2))
result = Application.Run("Mathematica", Array("$Version"))
result = Application.Run("Mathematica", Array("Date", Array()))

As you can see, Mathematica expressions are represented using 0-based, 1-D arrays. You can nest these as much as you want. The first (0) element of the array is the head of the function and the rest are arguments to the function. Symbols have no arguments. 0 arguments can be represented as shown above. When you evaluate an array-based expression, by default, results are returned in that form as well.

If you want to evaluate a text expression, you can do that too. In this case, by default, results are returned as text.

result = Application.Run("Mathematica", "Plus[2, 2]")
result = Application.Run("Mathematica", "$Version")
result = Application.Run("Mathematica", "Date[]")

An optional second argument allows you to specify a return format.

result = Application.Run("Mathematica", "Range[3]", "Expression")

'result is Array("List", 1, 2, 3)

result = Application.Run("Mathematica", Array("Range", 3), "Text")

'result is "{1, 2, 3}"

Returning results as native VBA arrays is also possible. An optional third argument can be used to specify options relating to how the array is formatted.

result = Application.Run("Mathematica", Array("IdentityMatrix", 2))

'result is Array("List", Array("List", 1, 0), Array("List", 0, 1))

result = Application.Run("Mathematica", Array("IdentityMatrix", 2), "Array")

'result is a native 2-D 0-based VBA array

result = Application.Run("Mathematica", Array("IdentityMatrix", 2), "Array", Array("Value", 2, 0))

'result is an array suitable for assigning to an Excel range

Normally, connecting to Mathematica is managed automatically, but if you want to connect and disconnect from Mathematica explicitly, you can.

Call Application.Run("Mathematica", True)
MsgBox Application.Run("Mathematica", "$Version")
Call Application.Run("Mathematica", False)