Object handles

Some Julia objects are large, or have no sensible representation on a worksheet: a big matrix, a fitted model, a DataFrame, a dictionary. Rather than returning such an object to Excel, JuliaCallHandle (and JuliaEval with ReturnHandle TRUE) keeps it in Julia and returns a handle, a short string naming it, such as jl:Array#17@k3x9. Pass the handle to any function in place of the object, and Julia receives the object itself:

CellFormulaResult
A1=JuliaEval("rand(1000, 1000)", TRUE)jl:Array#1@k3x9
A2=JuliaCall("sum", A1)the sum of the matrix's million elements
A3=JuliaCallHandle("inv", A1)jl:Array#2@k3x9, a handle to its inverse
A4=JuliaCall("maximum", A3)the inverse's largest element

The matrix is built once and stays in Julia, however many formulas use it. A handle can be passed to JuliaCall, JuliaCallNamedArgs, JuliaCallHandle and their VBA counterparts, including inside a range or array: a range of handles arrives in Julia as a vector of the objects. =JuliaCall("identity", A1) returns a handle's object to the worksheet as data. A handle's text is jl:<label>#<id>@<session>: the label is the object's type (or a label you choose, see below), for people reading the sheet, the id numbers each object, and the session identifies the Julia process holding it.

In the demo below, jl.sample (a worksheet function of your own, exposed with handle=true) returns a handle to 100 million random numbers - about 95 times as many as fit in a worksheet column. length, mean, std and jl.histogram all work on the same object in Julia, and only their small results come back to Excel. Changing σ rebuilds the sample and everything that uses it.

  • The annotations in brown text ("Formula at...") are to make what's happening in the demo clearer. They won't appear when you try CallFromExcel for yourself.
  • Replay the GIF by refreshing your browser (F5).

A worksheet function returning a handle to 100 million random numbers kept in Julia, with length, mean, std and a histogram computed from it, and recalculated when an input changes

The functions for handles are JuliaCallHandle, JuliaEvalHandle, JuliaHandleRelease, JuliaHandleReleaseAll and JuliaHandleInfo, and JuliaEval with ReturnHandle TRUE.

Points to note

Lifetime

A handle's object stays in Julia while a formula that creates it exists. Edit or delete that formula, or change its inputs, and the object is freed (and a new one created for new inputs). Excel sometimes frees an object only at a later recalculation, for example after a workbook is closed.

Same formula, same object

Formulas with the same function and the same arguments share one object, as do copies of a cell, and recalculating - even with Ctrl+Alt+F9 - doesn't rebuild it. So =JuliaEval("rand(3)", TRUE) keeps its first random numbers. To get a separate, or new, object, change an input, for example an extra argument that the Julia function ignores. The ribbon's Rebuild Objects button rebuilds every handle's object, for example after you change the Julia code that builds them; from VBA, Application.Run "JuliaRebuildObjects" does the same.

Volatile arguments

A handle formula can't keep a handle if its arguments change every time Excel recalculates it, as they do when it uses RAND, RANDARRAY or NOW, directly or through the cells it refers to. (Other volatile functions, such as OFFSET, INDIRECT and TODAY, are fine: they make the cell recalculate, but usually with the same arguments, so it keeps its handle.) For example, take this formula in automatic calculation:

=JuliaCallHandle("identity", RAND())
  1. Excel calculates the cell. RAND() gives, say, 0.42, so Julia builds an object for identity(0.42), and the cell gets a handle to it.
  2. The handle reaches the cell as an RTD update. Excel recalculates a cell to show each such update, up to one RTD throttle interval (2 seconds by default) later.
  3. In that recalculation, RAND() gives a new number, say 0.87. These are new arguments, so, as with any change of input (see Same formula, same object), Julia builds a new object, the cell gets a new handle, and the old object is freed.
  4. The new handle is another RTD update, so Excel recalculates the cell again, and so on, without end.

CallFromExcel notices after a few rounds (roughly 6 seconds by default) and stops the loop: the cell shows an error saying its arguments change at every recalculation. But RAND recalculates whenever anything in the workbook does, and the loop then starts again. Instead:

  • generate the data in Julia, e.g. =JuliaEval("rand(1000)", TRUE) rather than =JuliaCallHandle("identity", RANDARRAY(1000));
  • if the result needn't stay in Julia, use JuliaCall, e.g. =JuliaCall("sum", RANDARRAY(1000));
  • copy the volatile values and paste them as values;
  • or, to get a new object at every recalculation (F9), switch to manual calculation (Formulas > Calculation Options > Manual), where Excel doesn't recalculate after each new handle. Note that this setting applies to all open workbooks.

Don't change a handle's object

A function that changes its argument, such as push! or sort!, changes the stored object without changing its handle, so cells using it aren't recalculated, and results depend on the order Excel calculates in. Use functions that return a new object, such as sort, and make a new handle of the result.

When Julia restarts

JuliaLaunch (in a worksheet formula or from VBA), and the ribbon's Launch Julia button, notice a new Julia session and rebuild every handle's object in it, in the order Excel's dependencies require. A cell that defines functions the handles need should refer to the launch cell, so that it is recalculated first, e.g. =IF(LEN(Z1)>0, JuliaInclude("C:\MyCode\models.jl")) where Z1 holds =JuliaLaunch(). Until then - for example after Julia is restarted from the REPL with serve_xl - a handle from the old session gives an error saying it was not found.

Excel's RTD throttle interval

Handles use Excel's RTD (real-time data) mechanism, and Excel passes RTD updates to cells at most once per throttle interval: 2 seconds unless it has been changed. So after Julia restarts, or after Rebuild Objects, a handle cell can show #N/A for up to that long before it is rebuilt. In automatic calculation, a cell that has just created a handle is also recalculated once more, one interval later. This keeps the same handle and creates no new object. To see or change the interval, use VBA's Immediate window (Alt+F11, then Ctrl+G):

? Application.RTD.ThrottleInterval
Application.RTD.ThrottleInterval = 0    ' pass updates on as soon as possible

The setting applies to all of Excel, not just CallFromExcel. It affects every RTD source, such as market-data feeds, and Excel remembers it between sessions. A smaller interval makes rebuilds quicker, but other RTD feeds may then recalculate more often and use more CPU. You rarely need to change it.

Strings that look like handles are handles

Any string of the form jl:<label>#<id>@<session> is taken to be a handle, whether a formula returned it or it was typed. The whole string must have that form: <label> is any text without #, @, spaces or control characters (it may be empty), <id> is a number, and <session> is four letters and digits. If its object has been freed, or it comes from an earlier Julia session (for example, saved in a workbook), the call gives a "not found" error, rather than passing the string to Julia.

Errors pass through

If an argument to JuliaCallHandle, or to a function exposed with handle=true, is an error value, such as #N/A, it returns that error without calling Julia. (JuliaCall instead passes the error to Julia, as an ExcelError.) This is because a handle cell shows #N/A while its object is being built, and after Julia restarts until it is rebuilt: in a chain of handles, each cell waits for the one before it, rather than running its function on #N/A and creating an object that is replaced moments later. An error inside an array argument, such as a range containing #N/A, is passed to Julia as usual.

From VBA

VBA can pass handles from cells to jl.JuliaCall etc. Handles that VBA creates, with jl.JuliaCallHandle or jl.JuliaEvalHandle, belong to no formula, so they last until jl.JuliaHandleRelease or jl.JuliaHandleReleaseAll frees them, or Julia exits. (Calling the worksheet function through Application.Run or Evaluate gives a handle that is freed straight away.)

Labels for your own types

The label is the name of the object's type, without its module or parameters (Array for a Matrix{Float64}). To choose your own, add a method to CallFromExcel.handle_label, for example (on a bank's derivative desk) CallFromExcel.handle_label(x::YieldCurve) = "Curve_$(x.currency)_$(x.floatingindex)", so that a sheet shows jl:Curve_USD_SOFR#3@k3x9. The label is worked out once, when the handle is created, and any #, @, whitespace or control character in it is replaced by _.