???? 安裝配置完成后(與自定義函數(shù)UDFs的配置是一致的,加入xlwings加載項(xiàng),alt+F11中引用xlwings等等常規(guī)操作后),通過 “RunPython”調(diào)用python代碼。
范例:
VBA代碼如下:
Sub hi()
RunPython ("import sayhi; sayhi.sayhi()")? " sayhi為py文件名,sayhi()為sayhi.py中的自定義函數(shù)"
End Sub

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、在網(wǎng)上看到很多介紹的vba代碼都用from xw import sayhi,測試提示未發(fā)現(xiàn)xw模塊而報錯。
????? 2、在調(diào)用一次python代碼后,如果修改了代碼,再次執(zhí)行還是修改前的,這時需要點(diǎn)擊excel的xlwings部分import Functions重新載入才能生效