0

When I try to save the file, it doesn't save and fails.

I get the error:

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Save method of Application class failed', 'xlmain11.chm', 0, -2146827284), None)

Not sure what I'm doing wrong here. Some other posts seem to be pretty old and not relevant.

I saw a post saying to use SaveAs() but that errors out and says AttributeError: <unknown>.SaveAs. Did you mean: 'Save'?

My code:

import os, os.path
import win32com.client

# path = (r'C:\Users\christiansanchez\Downloads\')

if os.path.exists("test_macro.xlsm"):
    xl = win32com.client.Dispatch("Excel.Application")
    xl.Workbooks.Open(os.path.abspath("test_macro.xlsm"))
    xl.Application.Run("test_macro.xlsm!module1.test_macrob")
    xl.Application.Save("test_macro.xlsm")
    xl.Application.Quit("test_macro.xlsm")
else:
    print("error")
2
  • 1
    You want to call .Save on a Workbook object, not the Application. Btw, I don't think Quit has any parameters. Commented Feb 2, 2023 at 22:06
  • Also, xl.Application is superfluous. xl already refers to an Application object, just use xl.Workbooks.Open etc. Commented Feb 3, 2023 at 10:32

1 Answer 1

3

As per the comments, assign a variable to the opened workbook, and call Save() on that:

import os, os.path
import win32com.client

# path = (r'C:\Users\christiansanchez\Downloads\')

if os.path.exists('test_macro.xlsm'):
    xl = win32com.client.Dispatch('Excel.Application')
    wb = xl.Workbooks.Open(os.path.abspath('test_macro.xlsm'))
    xl.Run('test_macrob')
    wb.Save()
    xl.Quit()
else:
    print("error")

Notes:

  • Macro names are at global scope in Excel, so unless you have two sheets with the same macro name open you don't need to fully qualify the macro name.
  • The variable xl already refers to an Application object: you don't need xl.Application
Sign up to request clarification or add additional context in comments.

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.