Possible bug? xlwings cannot run an Excel macro? [

2019-07-13 18:02发布

This question already has an answer here:

I am having a problem getting xlwings to run a macro from Python. Despite following the code from xlwings documentation, I cannot get xlwings to execute an Excel macro. For instance, in Excel workbook named "Book.xlsm":

' in Excel workbook Book.xlsm
Sub Test()
   Set ws = Worksheets("ABC")
   ws.Range("A1").Value = 10
End Sub

This macro runs OK within Excel. But when I try calling this module from Python, it fails:

# in Python
import xlwings

wb = xlwings.Book('C:\\Book.xlsm')
wb.macro('Test')
print('done.')

No error messages. The Python code just runs and ends, printing the message "done." but when I check the worksheet ABC, nothing is written. Please note I am able to connect to this workbook and change cell values using xlwings. I just cannot get it to run the Test macro.

Also note I have used a much older xlwings (prior to 0.7.0, I think) before and it runs my macros with no problems. I am using the 0.10.0 version now.

1条回答
叼着烟拽天下
2楼-- · 2019-07-13 18:41

Try the following:

In VBA:

Sub Test(number)
   Set ws = Worksheets("Hoja1")
   ws.Range("A1").Value = number
End Sub

In python:

import xlwings as xw
wb1 = xw.Book('Libro1.xlsm')    
macro=wb1.macro('Test')
macro(10)
print('done.')
查看更多
登录 后发表回答