Situation
The xlwings package provides a convenient way to call python functions from an excel VBA module. The xlwings documentation gives the following basic example:
Write the code below into a VBA module.
Sub HelloWorld() RunPython ("import hello; hello.world()") End Sub
This calls the following code in
hello.py
:# hello.py import numpy as np import xlwings as xw def world(): wb = xw.Book.caller() wb.sheets[0].range('A1').value = 'Hello World!'
Trying to run the python function world()
directly (instead of calling it from excel VBA) gives the following error message:
Exception: Book.caller() must not be called directly. Call through Excel or set a mock caller first with Book.set_mock_caller().
Question
I would like to modify the world()
function such that it raises a custom exception instead when being run directly. In order to achieve this I first need to determine programmatically whether the world()
function is being run directly or being called from excel VBA (at least that's what I'd think). How could I do this?