Reputation: 1
I'm trying to write a code that would automatically save my excel sheets to PDF and got it to work but with certain files, Excel throws me an error that states "Document not saved. The document may be open, or an error may have been encountered when saving."
I've tried running the same code with other files and it seems to work for about half of them. I've tried to name the file as a different PDF name which still throws the same error for the same files.
import win32com.client as win32
Xlsx = win32.Dispatch('Excel.Application')
Xlsx.Visible = True
wb = Xlsx.Workbooks.Open('Sample')
wb.WorkSheets([3,4,5,6,7,8]).Select()
wb.ActiveSheet.ExportAsFixedFormat(0, 'Sample')
wb.Save()
wb.Close()
Xlsx.Quit()
del wb
del Xlsx
Upvotes: 0
Views: 621
Reputation: 442
I would put this as a comment but I don't have enough kudos to do that yet. I would suggest that the issue is probably that some of the files are larger, and for whatever reason the file takes longer to save and therefore there is an issue at the point that the file is being closed (but not yet saved). I think therefore if you put a time pause for a few milliseconds, after the export and/or before the close, it will deal with this.
Initially you could try the following for a one second delay:
import time
time.sleep(1)
If that deals with the issue, you could then decrease to 100 milliseconds with time.sleep(.100) and test again.
Upvotes: 0