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,11111est'

 Place 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重新载入才能生效

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。