0

I'm trying to run simple Excel macro via Python using xlwings but it doesn't work.

I tried to run Python in JupyterLab. Both code, VBA and Python, are so simple and when I run VBA code in Excel, it works correctly. Also, I tried some simple python code using xlwings like

import xlwings as xw

wb = xw.Book('test.xlsm')
sheet = wb.sheets[0]
sheet.range('A1').value = 'test'

works correctly.

However, the python code below doesn't work.

import xlwings as xw

wb = xw.Book('test.xlsm')
macro = wb.macro('test')
macro()

I put this VBA code below on "ThisWorkbook" in ExcelVBA editor.

Sub test()
    Range("A1").Value = "This is a test."
End Sub

Error message is like this.

com_error: "Cannot run the macro 'test.xlsm'!test'. The macro may not be available in this workbook or all macros may be disabled."

2 Answers 2

2

I solved it by myself.

I edited the code like this and it works correctly.

macro = wb.macro('ThisWorkbook.test')
Sign up to request clarification or add additional context in comments.

Comments

0

Your macro is defined in ThisWorkbook, but xlwings expects it to be in a standard module, not in the workbook object or a worksheet module. Macros in ThisWorkbook or Sheet1, etc., are not directly accessible via wb.macro('macro_name').
A Sub (procedure that does not return a value, you can access it via
wb.macro('ThisWorkbook.test')

However, Python cannot read the return value of a function if it is inside Sheet1 or ThisWorkbook. If you have your legacy code where functions are written in Sheet/workbook module, you have two options:

wb.macro("ThisWorkbook.SOME_FUNCTION") # Will NOT return value to Python (None)
  1. Move them into a standard module, or

  2. Create a wrapper function in a standard module that calls the legacy function, and then call the wrapper from Python.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.