从xlwings返回值到vba

问题描述 投票:3回答:1

让我们使用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文档中?

谢谢你的任何指示。

python vba excel-vba xlwings excel
1个回答
2
投票

RunPython不允许您根据xlwings文档返回值。要解决这些问题,请使用UDF,请参阅VBA:用户定义函数(UDF) - 但是,目前仅限于Windows。

https://docs.xlwings.org/en/stable/udfs.html#udfs

© www.soinside.com 2019 - 2024. All rights reserved.