vba python 结合_xlwings利用VBA调用python

安装配置完成后(与自定义函数UDFs的配置是一致的,加入xlwings加载项,alt+F11中引用xlwings等等常规操作后),通过 “RunPython”调用python代码。

范例:

VBA代码如下:Sub hi()

RunPython ("import sayhi; sayhi.sayhi()") " sayhi为py文件名,sayhi()为sayhi.py中的自定义函数"

End Sub

VBA调用python范例

python代码如下:import xlwings as xw

def sayhi():

wb=xw.Book.caller()

wb.sheets[0].range(A1).value=Hello,world,11111estPlace xw.Book.caller() within the function that is being called from Excel and not outside asglobal variable. Otherwise it prevents Excel from shutting down properly upon exiting andleaves you with a zombie process when you useOPTIMIZED_CONNECTION=True.

注:

1、在网上看到很多介绍的vba代码都用from xw import sayhi,测试提示未发现xw模块而报错。

2、在调用一次python代码后,如果修改了代码,再次执行还是修改前的,这时需要点击excel的xlwings部分import Functions重新载入才能生效

安装配置完成后(与自定义函数UDFs的配置是一致的,加入xlwings加载项,alt+F11中引用xlwings等等常规操作后),通过 “RunPython”调用python代码。 范例: VBA代码如下:Sub hi() RunPython ("import sayhi; sayhi.sayhi()") " sayhi为py文件名,sayhi()为sayhi.py中的自定义函数" End Sub VBA调用python范例 python代码如下:import xlwings as xw def sayhi(): wb=xw.Book.caller() wb.sheets[0].range(A1).value=Hello,world,11111estPlace xw.Book.caller() within the function that is being called from Excel and not outside asglobal variable. Otherwise it prevents Excel from shutting down properly upon exiting andleaves you with a zombie process when you useOPTIMIZED_CONNECTION=True. 注: 1、在网上看到很多介绍的vba代码都用from xw import sayhi,测试提示未发现xw模块而报错。 2、在调用一次python代码后,如果修改了代码,再次执行还是修改前的,这时需要点击excel的xlwings部分import Functions重新载入才能生效
经验分享 程序员 微信小程序 职场和发展