让我们使用xlwings documentation上的示例。
给出以下python代码:
import numpy as np
from xlwings import Workbook, Range
def rand_numbers():
""" produces std. normally distributed random numbers with shape (n,n)"""
wb = Workbook.caller() # Creates a reference to the calling Excel file
n = int(Range('Sheet1', 'B1').value) # Write desired dimensions into Cell B1
rand_num = np.random.randn(n, n)
Range('Sheet1', 'C3').value = rand_num
这是最初的例子。
假设我们将其略微修改为:
import numpy as np
from xlwings import Workbook, Range
def rand_numbers():
""" produces std. normally distributed random numbers with shape (n,n)"""
wb = Workbook.caller() # Creates a reference to the calling Excel file
n = int(Range('Sheet1', 'B1').value) # Write desired dimensions into Cell B1
rand_num = np.random.randn(n, n)
return rand_num #modified line
我们使用以下调用从VBA调用它:
Sub MyMacro()
dim z 'new line'
z = RunPython ("import mymodule; mymodule.rand_numbers()")
End Sub
我们将z
作为空值。
有没有办法直接将值返回给vba而不写入文本文件,或者将值首先放在excel文档中?
感谢您的任何指示。
答案 0 :(得分:1)
RunPython不允许您根据xlwings文档返回值 。 为了克服这些问题,请使用UDF,请参阅VBA:用户定义的函数(UDF)-但是,当前仅限于Windows。