xlwings: Unable to import functions (UDFs) via xlwings ribbon

Viewed 1565

I'm trying to import a user-defined function(UDF) via xlwings but am encountering an issue. Upon pressing the import functions button in the xlwings ribbon, I receive the following run time error:

`Run_time error '1004 

`Method of 'VBProject' of object '_Workbook' failed.'

According to the VBA debugger, the below module contains the problem:

Sub ImportXlwingsUdfsModule(tf As String)
     ' Fallback: This is called from Python as direct pywin32 calls were 
     '  sometimes failing, see comments in the Python code
     On Error Resume Next
     ActiveWorkbook.VBProject.VBComponents.Remove 
     ActiveWorkbook.VBProject.VBComponents("xlwings_udfs")
     On Error GoTo 0
     **ActiveWorkbook.VBProject.VBComponents.Import tf**
End Sub

The .py file containing the UDF is saved in the same folder as the calling .xlsm workbook.

How do I rectify this so I can utilize UDFs?

2 Answers

If you have trusted access to the VBA object model and you are getting a TypeError, there is an additional answer that applies to both versions 0.22.2 and 0.22.3 and maybe earlier.

In file Lib>Site-Packages>xlwings>udfs.py on line 651 or 652 (depending on the version) insert ".Item" where shown in the following:

xl_workbook.VBProject.VBComponents.Remove(xl_workbook.VBProject.VBComponents.Item("xlwings_udfs"))

I do not know why this works but it does. The original line does work in VBA with only modifications that apply to VBA syntax and the workbook reference. (i.e. see the VBA code in the question for an example.

Related