RunPython¶
xlwings加载项¶
要用 Run main
按钮(v0.16的新功能)或者 RunPython
VBA函数,需要xlwings加载项(或VBA模块),参见 Add-in & Settings.
对新项目,最简单的办法是通过命令行客户端的的quickstart命令,详见 Command Line Client (CLI)
$ xlwings quickstart myproject
用"RunPython"调用Python¶
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; hello.world()"
End Sub
上面代码会调用 hello.py
中的内容:
# hello.py
import numpy as np
import xlwings as xw
def world():
wb = xw.Book.caller()
wb.sheets[0]['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.