Possible bug? xlwings cannot run an Excel macro? [duplicate]

南楼画角 提交于 2020-01-15 01:51:10

问题


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:


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.')


来源:https://stackoverflow.com/questions/40201831/possible-bug-xlwings-cannot-run-an-excel-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!