我想用pythonyield通过xlwings将变量传递到我的VBA中,但没有';好像不行
我试图从python函数中产生一些变量,以传递到我的VBA代码中。但我似乎无法让它发挥作用。数据来自一个名为rngTest的范围名称 在我的子程序中,我有以下代码调用python函数调用foo_func() Python代码我想用pythonyield通过xlwings将变量传递到我的VBA中,但没有';好像不行,python,python-3.x,xlwings,Python,Python 3.x,Xlwings,我试图从python函数中产生一些变量,以传递到我的VBA代码中。但我似乎无法让它发挥作用。数据来自一个名为rngTest的范围名称 在我的子程序中,我有以下代码调用python函数调用foo_func() Python代码 # -*- coding: utf-8 -*- import xlwings as xw def foo_func(): wb = xw.Book.caller() rngTest = wb.sheets["Data"].range("rngTest")
# -*- coding: utf-8 -*-
import xlwings as xw
def foo_func():
wb = xw.Book.caller()
rngTest = wb.sheets["Data"].range("rngTest").value
for idx, test in enumerate(rngTest):
i = str(idx + 3)
yield i
wb.sheets["Data"].range(f"F{i}").value = test
VBA代码
Sub Call_Python_Function()
Dim x As String
x = RunPython("import xlwings_test; xlwings_test.foo_func()")
Debug.Print (x)
Dim y As String
y = "This is y"
Debug.Print (y)
End Sub
我还尝试创建一个UDF
@xw.func
def my_udf():
for i in range(0, 10):
yield i
VBA
子调用_Python_函数()
但是由于它是作为生成器对象出现的,所以得到这个错误
使用
RunPython
无法做到这一点。为此,需要使用用户定义函数(UDF),请参阅。以下是在Python中定义UDF的方式:
import xlwings as xw
@xw.func
def double_sum(x, y):
"""Returns twice the sum of the two arguments"""
return 2 * (x + y)
谢谢我这样做了,但是在VBA中捕获变量时出现另一个错误,类型生成器的对象,无法转换为COM变量您不能使用
yield
,而是使用return
。
import xlwings as xw
@xw.func
def double_sum(x, y):
"""Returns twice the sum of the two arguments"""
return 2 * (x + y)