To get access to
Run main (new in v0.16) button or the
RunPython VBA function, you’ll need the xlwings addin (or VBA module), see Add-in & Settings.
For new projects, the easiest way to get started is by using the command line client with the quickstart command, see Command Line Client (CLI) for details:
$ xlwings quickstart myproject
Call Python with 「RunPython」¶
In the VBA Editor (
Alt-F11), write the code below into a VBA module.
xlwings quickstart automatically
adds a new module with a sample call. If you rather want to start from scratch, you can add new module via
Insert > Module.
Sub HelloWorld() RunPython ("import hello; hello.world()") End Sub
This calls the following code in
# hello.py import numpy as np import xlwings as xw def world(): wb = xw.Book.caller() wb.sheets.range('A1').value = 'Hello World!'
You can then attach
HelloWorld to a button or run it directly in the VBA Editor by hitting
xw.Book.caller() within the function that is being called from Excel and not outside as
global variable. Otherwise it prevents Excel from shutting down properly upon exiting and
leaves you with a zombie process when you use
Use UDF Server = True. Note that you need to decorate
the function with @xw.sub if you want to run it with
Use UDF Server enabled.
Function Arguments and Return Values¶
While it’s technically possible to include arguments in the function call within
RunPython, it’s not very convenient.
RunPython does not allow you to return values. To overcome these issue, use UDFs, see User Defined Functions (UDFs) - however,
this is currently limited to Windows only.