user1388142
user1388142

Reputation: 603

run excel macro in python and save the results

I have two files, namely "macro.xlms" and "data.csv"

I want to run the macro [Analyze] from macro.xmls file on data.csv to generate some data and save the results

So far my code is:

macroPath="Macro.xlsm"
filePath="Output.csv"

def performAnalysis():

    if os.path.exists(macroPath):    
        excel = win32com.client.Dispatch("Excel.Application")
        excel.Visible= True
        excel.Workbooks.Add(filePath)       
        excel.Application.Run(macroPath+"!Analyze")
        excel.Application.Quit()
        del excel
    else:
        print("Error")

def main():
    performAnalysis()

main()

When I run the above I get the following error message:-

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'C:\\Users\\Nabeel\\Desktop\\dense_breasts_experiments\\VolparaOutputExcelMacroOnly_Nov20thV1.xlsm!VolparaAnalyze'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)

Can anyone please guide me what I am doing wrong ?

Code Edit:

def performAnalysis():


    if os.path.exists(macroPath):
        excel = win32com.client.Dispatch("Excel.Application")
        excel.Visible= True
        excel.Workbooks.Open(filePath)  
        excel.Workbooks.Open(macroPath)    
        excel.Application.Run(macroPath+"!Analyze")         

def main():
    performAnalysis()

main()

still getting the same error

Upvotes: 2

Views: 2127

Answers (1)

Veljko Jovanovic
Veljko Jovanovic

Reputation: 69

Not sure whcih library are you using but win32com has an option to save changes and all you have to to is add the following line:

excel.ActiveWorkbook.Saved = True

Also, excel stands for win32.DispatchEx('Excel.Application') after win32com.client is imported.

Let me know if it works!

Upvotes: 2

Related Questions