Julia API

The Julia functions of the CallFromExcel package that you might call yourself. The worksheet functions, which are part of the Excel add-in, are documented in Worksheet functions and VBA functions.

Installation

CallFromExcel.installme — Function
installme()

Install CallFromExcel's Excel add-in for the current user, from this version of the package, and uninstall JuliaExcel's add-in if present. Needs no admin rights. Close Excel first: the installer stops with an error if Excel is running.

Run it after installing CallFromExcel, and again after each update: the add-in and the Julia package must be the same version. If they aren't, Excel says so on launching Julia.

source

Your own worksheet functions

CallFromExcel.@excel — Macro
@excel [name="..."] [description="..."] [argdescriptions=[...]] [broadcast=...] [handle=...] [volatile=...] function f(...) ... end

Define a function and make it callable from Excel, as jl.f by default, following the method defined here, whatever other methods f has. Options are as for expose_to_excel, e.g. @excel broadcast=true f(x, y) = .... A docstring goes before @excel, as before the function.

"""
    birthday(people, days=365)

The probability that, in a group of people, at least two share a birthday.

# Arguments
- `people`: the number of people in the group.
- `days`: the number of days in the year.
"""
@excel broadcast=true function birthday(people, days=365)
    1 - prod((days - k) / days for k in 0:people-1)
end
source
CallFromExcel.expose_to_excel — Function
expose_to_excel(fn_name; name=nothing, nargs=nothing, method=nothing, description="", argdescriptions=String[], broadcast=false, handle=false, volatile=false)
expose_to_excel(f::Function; ...)

Make a Julia function, named by fn_name (evaluated in Main) or given itself, callable from Excel as a worksheet function, by default jl.<its name>. Returns the Excel name and the method it follows, such as "jl.bitstring follows bitstring(x::T) where T @ Base intfuncs.jl:1095, chosen from 2 methods" - shown in the cell when called with JuliaEval; "chosen from" marks a guess (see below). The add-in registers exposed functions after JuliaLaunch, JuliaInclude and JuliaEval, and when the ribbon's Register Functions button is clicked (for functions exposed from the REPL). @excel does the same for the method it's attached to.

Which method

Whichever method is called is chosen by Julia's dispatch, from the arguments Excel passes; but Excel shows one method's arguments, names and description, needs to know which arguments may be left out, and broadcast=true goes by its declared argument types. When a function has several methods, expose_to_excel makes an informed guess - preferring methods that can take what a worksheet passes, then the most general - and says which method it chose (in what it returns, and in the REPL), unless told:

  • method=m: the method m itself. The surest way is to ask which for the method that values from Excel will reach: numbers arrive as Float64, text as String, a column as a Vector and a row or block as a Matrix (see Marshalling in the documentation), so expose_to_excel(quantile; method=which(quantile, (Vector{Float64}, Float64))) follows the method that =jl.quantile(A1:A100, 0.95) calls.
  • nargs=n: the method with n positional arguments, counting those with default values, the best by the same guess if there are several. expose_to_excel(eigvals; nargs=1) gives eigvals(A).

Use method when the guess is wrong (the tooltip shows unexpected argument names), and in files included at every start-up, where a package update adding methods could change the guess.

Trailing arguments are optional in Excel when a method without them takes the same first arguments, by name: those with default values (f(a, b=2)), and those of a method such as cond(x) alongside cond(x, p). Left out at the end of a call, they aren't passed, and Julia calls the method that takes the arguments given.

expose_to_excel(bitstring)                       # =jl.bitstring(0.1)
expose_to_excel(LinearAlgebra.eigvals; nargs=1)  # =jl.eigvals(A1:C3)
expose_to_excel(evalpoly; broadcast=true)        # =jl.evalpoly(A1:A20, B1:B3), a column

Descriptions, shown by Excel's Function Wizard and IntelliSense, come from the function's docstring unless given: the text after the signature, up to the first heading, describes the function, and an # Arguments list ($- `name`: description$) its arguments. IntelliSense's tooltip shows them in full, keeping paragraphs and list items but leaving out code blocks, admonitions and footnotes, with simple LaTeX maths as plain text; the Function Wizard, limited by Excel to 255 characters, shows the first paragraph of the description, and each argument's description, shortened to fit. argdescriptions replaces the docstring's, position by position, where not empty.

Broadcasting

A range arrives as it does with JuliaCall (a column as a vector, a row or a block as a matrix), and by default the function receives it whole. A range given to a broadcasting argument is instead broadcast over, as f.(...) would, so a function written for single values works on ranges, with one call from Excel. Other arguments are passed whole to every call. Which arguments broadcast:

  • broadcast=false (the default): none.
  • broadcast=true: all, except any declared with an array type, such as c::AbstractVector or m::Matrix{Float64}, which are passed whole.
  • broadcast=(:a, :b), or broadcast=:a for one: those named.

Ranges broadcast together must have the same number of rows, or one of them a single row (and likewise columns); a column against a row gives a table, as in Excel.

Handles

With handle=true, the Excel function returns a handle to the result, which stays in Julia, as JuliaCallHandle does: for a fitted model, a large matrix or anything else that belongs in Julia rather than on the sheet. The same arguments give the same object, built once. With broadcasting, the handle is to the whole broadcast result. The description shown in Excel ends "Returns a handle."

Volatile functions

With volatile=true, Excel recalculates the function at every calculation, as it does NOW and RAND, rather than only when its arguments change: for a function that reads something Excel can't see, such as a Julia global set by JuliaSetVar or JuliaEval, a file, a database, the clock or a random number generator. Use it sparingly: every calculation calls Julia for every cell using the function, and recalculates the cells that depend on them. volatile=true can't be combined with handle=true, since a handle keeps its object while the arguments are unchanged.

source

Object handles

CallFromExcel.handle_label — Function
handle_label(x)

The label in a handle for x, jl:<label>#<id>@<session>, for people reading the sheet - looking up the object ignores it. By default the name of x's type, without its module or parameters: Array for a Matrix{Float64}, Dict for a Dict{String,Int}.

Add methods for your own types to choose a more informative label, for example:

CallFromExcel.handle_label(x::YieldCurve) = "Curve_$(x.currency)"

so that a handle to a US dollar curve reads jl:Curve_USD#3@k3x9. The label is worked out once, when the handle is created. Any #, @, whitespace or control character in it is replaced by _, since # and @ mark where the id and session start.

source

Attaching to a running Julia session

CallFromExcel.serve_xl — Function
serve_xl(show_results::Bool=true, pid::Integer=0)

Attaches this Julia session to an Excel process, so it responds to JuliaCall/JuliaEval requests from that Excel session exactly as if it had been launched by the JuliaLaunch() worksheet function.

show_results is passed to display_results - it defaults to true here, since attaching an interactive session like this is exactly when seeing each call and its result echoed to the REPL is most useful.

pid identifies the Excel process to attach to. Leave it at its default of 0 to attach to the single running Excel process automatically - if none is found, or more than one is, throws an error explaining how to call serve_xl with pid given explicitly. Get pid from Excel's JuliaExcelPID() worksheet function.

Given explicitly, pid is checked against the running Excel processes (Windows only - this check is skipped, not enforced, when Julia itself is running under WSL) and an error thrown if it doesn't match one, rather than silently starting a server nothing will ever connect to.

Also throws if Excel already has another Julia session listening for it (e.g. one launched via JuliaLaunch, or attached earlier with serve_xl itself) - starting a second one wouldn't do anything useful, since Excel would keep talking to whichever session it's already connected to. Stop that session first (e.g. call stop_server() there, or close it) before attaching this one.

source
CallFromExcel.stop_server — Function
stop_server()

Stops this Julia session's HTTP server, if one is running, so it no longer responds to JuliaCall/JuliaEval requests from Excel. No-op if no server is currently running.

Also clears the port from this session's window title (via settitle) - otherwise the title would keep claiming a port this session no longer serves, which could wrongly look like a match for whichever port a different session (e.g. one started with serve_xl) happens to pick up next.

Leaves the port file on disk untouched, so Excel will still try the now-dead port on its next request - and get a clean "no connection" error rather than reaching this session again.

source
CallFromExcel.server_status — Function
server_status()

Returns a NamedTuple (running, pid, port, display_results) describing this Julia session's HTTP server: running is true if a server is currently listening; pid is the Excel process id it's set up to serve (0 if setxlpid has never been called), regardless of whether the server is currently running; port is the port it's listening on, or 0 if not running; display_results is the current setting of display_results().

source

Debugging

CallFromExcel.display_results — Function
display_results(switch::Bool)

Switch on or off display in the REPL of both the incoming expression/function call from Excel and the value returned to Excel, for calls via JuliaCall and JuliaEval.

source
display_results()

Returns whether display in the REPL of results of calls from Excel is currently switched on.

source
CallFromExcel.answer_again — Function
answer_again()

Evaluates last_question again, and you can wrap it with @enter or your own debugging tools. Useful for interactively debugging a JuliaCall/JuliaEval that failed (or just misbehaved) when called from Excel, without needing to repeat the call from there.

Uses Meta.parseall rather than Meta.parse since last_question set by srv_eval_inner can be a multi-statement, newline-separated string (see its docstring) - Meta.parseall also handles the single-statement string that srv_call_inner sets last_question to, so this is correct either way.

See also last_question, last_answer, args_from_xl.

source

The variables last_question, last_answer, args_from_xl and kwargs_from_xl are described in Debugging.

Types

CallFromExcel.ExcelError — Type
ExcelError(code::Int)

Represents an Excel error value (e.g. #DIV/0!, #N/A) received from Excel. Decoded from the wire format's ! type indicator (see decode_from_xl in decode.jl) and re-encoded the same way by encode_for_xl (encode.jl), so an Excel error round-trips through Julia unchanged - e.g. JuliaCall("identity", SomeErrorCell) returns the same error.

A Julia function that isn't written to expect an Excel error, and receives one where it expects an ordinary value, fails immediately with a MethodError. Functions that want to handle Excel errors explicitly can dispatch on this type, e.g. myfunc(::ExcelError) = missing to swallow them, or myfunc(e::ExcelError) = e to propagate them onward unchanged.

The numeric code is stored as-is, with no validation against the current list of known Excel error codes - Excel could add new ones in future versions, and any code decodes/re-encodes identically regardless of whether it's recognised (see EXCEL_ERROR_NAMES below, used only for display).

source