简体   繁体   中英

Can not run Excel macro via Python using xlwings

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."

I solved it by myself.

I edited the code like this and it works correctly.

macro = wb.macro('ThisWorkbook.test')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM