要用 Run main 按钮(v0.16的新功能)或者 RunPython VBA函数,需要xlwings加载项(或VBA模块),参见 Add-in & Settings.

对新项目,最简单的办法是通过命令行客户端的的quickstart命令,详见 Command Line Client (CLI)

$ xlwings quickstart myproject


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 a new module via Insert > Module.

Sub HelloWorld()
    RunPython "import hello;"
End Sub

上面代码会调用 中的内容:

import numpy as np
import xlwings as xw

def world():
    wb = xw.Book.caller()
    wb.sheets[0].range('A1').value = 'Hello World!'

你可以把 HelloWorld 绑定到一个按钮上,或者直接在VBA编辑器中通过点击 F5 运行。


Place 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.


While it’s technically possible to include arguments in the function call within RunPython, it’s not very convenient. Also, RunPython does not allow you to return values. To overcome these issues, use UDFs, see User Defined Functions (UDFs) - however, this is currently limited to Windows only.