Question

When I currently attempt to save an XLSM file like so:

from win32com.client import Dispatch

# Open Excel workbook
xl = Dispatch("Excel.Application")
wb = xl.Workbooks.Add(r"C:\Users\ryan\Desktop\Book1.xlsm")

# Make some changes
# blah blah blah

# Save the workbook in XLSM format with new name

wb.SaveAs(r"C:\Users\ryan\Desktop\Book1 - XLSM.xlsm")
xl.Quit()

I am given the following error...

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<COMObject Add>", line 7, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel'
, 'This extension can not be used with the selected file type. Change the file e
xtension in the File name text box or select a different file type by changing t
he Save as type.', 'xlmain11.chm', 0, -2146827284), None)

How do I save as a new file format?

Note- this causes the same error when trying to save a file that was already an XLSM, as an XLSM.

Was it helpful?

Solution

The format of the file is determined by the FileFormat parameter that you specify when you call SaveAs. Since you don't specify a value, the default value of .xlsx is chosen. The documentation lists the possible values. You need to use xlOpenXMLWorkbookMacroEnabled.

The code would be:

xlOpenXMLWorkbookMacroEnabled = 52
....
wb.SaveAs(filename, FileFormat=xlOpenXMLWorkbookMacroEnabled)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top