我想使用 xlwings 将变量传递到我的 VBA 和 python yield 但似乎不起作用
I want to pass variables into my VBA with python yield using xlwings but doesn't seem to work
我正在尝试从 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").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
子 Call_Python_Function()
Dim x As String
x = my_udf()
Debug.Print (x)
End Sub
但出现此错误,因为它作为生成器对象出现。
你不能用 RunPython
做到这一点。您需要为此使用用户定义函数 (UDF),请参阅 the docs。这就是在 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)
我正在尝试从 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").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 子 Call_Python_Function()
Dim x As String
x = my_udf()
Debug.Print (x)
End Sub
但出现此错误,因为它作为生成器对象出现。
你不能用 RunPython
做到这一点。您需要为此使用用户定义函数 (UDF),请参阅 the docs。这就是在 Python:
import xlwings as xw
@xw.func
def double_sum(x, y):
"""Returns twice the sum of the two arguments"""
return 2 * (x + y)