Home » excel » python – return value to vba from xlwings

python – return value to vba from xlwings

Posted by: admin April 23, 2020 Leave a comment

Questions:

Let’s use the example on xlwings documentation.

Given the following python code:

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

This is the original example.

Let’s say we modify it slightly to be:

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

And we call it from VBA using the following call:

Sub MyMacro()
    dim z 'new line'
    z = RunPython ("import mymodule; mymodule.rand_numbers()")
End Sub

We get z as an empty value.

Is there any way to return a value to vba directly without writing to a text file, or putting the value first in the excel document?

Thank you for any pointers.

How to&Answers:

RunPython does not allow you to return values as per xlwings documentation.
To overcome these issue, use UDFs, see VBA: User Defined Functions (UDFs) – however, this is currently limited to Windows only.

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