I am trying to build a xlwings UDF function which calculates results for specified scenarios. The code works usings Jupyter Notebook (i.e. without UDF). However, when I implement as UDF (using Windows) the function just returns "Automatisierungsfehler" (automation error) in the cell where the function is entered. So no issues when importing the function but when it is actually calculating...
Input for the function:
- x: cells with values to be replaced with scenario values
- y: cells with scenario values
- z: cell with result
Here is my code:
import xlwings as xw
@xw.func
@xw.arg('x', xw.Range)
@xw.arg('y',xw.Range)
@xw.arg('z',xw.Range)
@xw.ret(expand = "vertical")
def calc_scenario(x,y, z):
address = x.address
formula = x.formula
res = []
for scenario in y.value:
x.value = scenario
res.append(z.value)
x.formula = formula
return res
When using this code in excel I can import the function with no problem. When using it the formula (=calc_scenario(...)) just returns "Automatisierungsfehler".
The same code works from Jupyter Notebook:
import xlwings as xw
sht = xw.Book("TestStuff.xlsm").sheets[0]
def calc_scenario(x,y, z):
address = x.address
formula = x.formula
res = []
for scenario in y.value:
x.value = scenario
res.append(z.value)
x.formula = formula
return res
x = sht.range("C43:H43")
y = sht.range("C47:H49")
z = sht.range("C45")
calc_scenario(x,y,z)
Any ideas?
Thanks!