I already saw this question in other link but I'm new here and i don't have reputation to comment there.
I made the script works and the macro run but when saving the file instead of just saving, it opens a excel pop-up asking if i confirm the changes. How do I save directly without opening this pop-up?
my code (edited):
import os.path
import win32com.client as wincl
if os.path.exists("C:\\Users\\peo_cpena\\Downloads\\excel.xlsx"):
try:
xl = wincl.Dispatch("Excel.Application")
xl.Workbooks.Open(os.path.abspath(
"C:\\Users\\peo_cpena\\Downloads\\excel.xlsx"))
xl.Application.Run("macro2.xlsm!Macro2")
xl.Application.Workbooks("excel.xlsx").Save()
xl.Application.DisplayAlerts = False
xl.Application.Workbooks("excel.xlsx").Quit(False)
del xl
except:
xl.Application.Quit()
print("It didn't work")
del xl
Removing the Try i received this error:
Traceback (most recent call last):
File "C:/Users/peo_cpena/PycharmProjects/Cursoemvideo/UOL/CalculoImpARG.py", line 14, in <module>
xl.Application.Workbooks("C:\\Users\\peo_cpena\\Downloads\\Vendas_por_Repasse_Aeria_Games_Europe_GmbH_01102020-31102020.xlsx").Save()
File "C:\Users\peo_cpena\PycharmProjects\Cursoemvideo\venv\lib\site-packages\win32com\client\dynamic.py", line 197, in __call__
return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
pywintypes.com_error: (-2147352567, 'Exceção.', (0, None, None, None, 0, -2147352565), None)
Try explicitly saving the workbook before closing it:
xl.Application.Workbooks("excel.xlsx").Save()
xl.Application.Workbooks("excel.xlsx").Close(False)
Related
I have a code to work with an already open Excel file (it actually just closes it so the rest of the code can work, and then opens it again at the end). It works in one of my computers, but not in the other - I'm getting the following error:
Traceback (most recent call last):
File "tkinter\__init__.py", line 1892, in __call__
file "executavel.py", line 48, in GetSquareRoot
File "site-packages\win32com\client\dynamic.py", line 527, in __getattr__
AttributeError: Excel.Application.Workbooks
Here is the part of the code that raises the error (line 48 is "wb = xlApp.Workbooks.Open(path)"):
xlApp = client.GetObject(None, "Excel.Application")
wb = xlApp.Workbooks.Open('planilha.xlsx')
wb.Save()
wb.Close()
All Excel windows are closed except for the spreadsheet in question (there are no open pop-ups or anything). Is there a way to make this code work in both computers, or another way to close an already open Excel workbook?
Thanks!
I'm using openpyxl to modify some excel document but it doesn't actualize the calculated cells inside that document. It seems I must open the document with excel. I found this link.
But it fails finding my document. How is that possible? Could someone help on that specific point please?
Here is what I get:
>>> os.listdir()
['R_F.xlsx']
>>> import win32com.client
>>> xl = win32com.client.DispatchEx("Excel.Application")
>>> wb = xl.workbooks.open("R_F.xlsx")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<COMObject <unknown>>", line 2, in open
pywintypes.com_error: (-2147352567, 'Une exception s’est produite.', (0, 'Microsoft Excel', "Désolé... Nous ne trouvons pas R_F.xlsx. Peut-être l'avez-vous déplacé, renommé ou supprimé\xa0?", 'xlmain11.chm', 0, -2146827284), None)`
Same does happen when trying to open a word document. It doesn't find it! Very strange.
[USING XLWINGS PACKAGE]
I'm attempting to open an excel spreadsheet (existing), write data to specified cells, and then use the workbook.save() function to save the file to a new file name (as not to overwrite)
Right now I currently have:
app = xw.App(visible = False)
wbMain = wx.Book('Example.xlsm') #Open premade excel file
sheetMain = wbMain.sheets['Example']
sheetMain.range('A1').value = 'Test' #Modify value of cell A1
wbMain.save('NewFileName.xlsm') #Save to new filename
wbMain.close() #Close current excel sheet
app.kill() #Kill program (may not work)
(Sorry about my formatting if it's off)
Here is my traceback:
Traceback (most recent call last):
File "C:\Users\USER\Desktop\test_proj\main.py", line 34, in <module>
wbMain.save(NewFileName.xlsm)
----
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\main.py", line 688, in save
return self.impl.save(path)
---
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\_xlwindows.py", line 472, in save
self.xl.SaveAs(os.path.realpath(path))
----
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\_xlwindows.py", line 63, in __call__
v = self.__method(*args, **kwargs)
---
File "<COMObject Open>", line 7, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft
Excel', 'SaveAs method of Workbook class failed', 'xlmain11.chm', 0,
-2146827284), None)
I've tried lookin at the XLWings documentation and various other stackoverflow threads but none seemed to offer a solution that worked. Has anyone had the same issue before?
I had the same problem - turns out using the full path in wbMain.save('C:/xxx/NewFileName.xlsm') worked for me.
Credits to #aneroid for the help! See here: xlwings: Save and Close
Trying to run an Excel macro via Python I get the following error:
Traceback (most recent call last):
File ".\test.py", line 17, in <module>
xlApp.Application.Run(MACRO)
File "<COMObject <unknown>>", line 14, in Run
File "C:\Users\twauchop\Desktop\Python\virtual_envs\gutenberg\lib\site-packages\win32com\client\dynamic.py", line 287, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Cannot run the macro 'test'. The macro may not be available in this workbook or all macros may be disabled.", 'xlmain11.chm', 0, -2146827284), None)
I tried many of the fixes suggested in other questions.
I tried 'xlApp.Application.Run(wb.name + "!" + MACRO)'.
Is this a naming convention issue? I enabled everything via Trust Center and changed the VBA sub to public.
As a side-note, I also cannot run macros from the programmatically opened workbook (i.e. if I try manually). If I open the workbook manually, however, everything is fine.
I am running Python 3.6.5 on a 64 bit system, Windows 10.
Python:
import win32com.client
import os
import traceback
DIRECTORY = r'C:\\Users\\twauchop\\Desktop\\Excel\\'
FILE = 'test.xlsb'
MACRO = 'test'
path = os.path.join(DIRECTORY, FILE)
if os.path.exists(path):
try:
xlApp = win32com.client.Dispatch('Excel.Application')
xlApp.DisplayAlerts = False
xlApp.Visible = True
wb = xlApp.Workbooks.Open(Filename=path, ReadOnly=1)
xlApp.Application.Run(MACRO)
wb.Close(SaveChanges=1)
xlApp.Application.Quit()
print('Code ran successfully.')
except:
print('An error was encountered; see traceback.')
print(traceback.format_exc())
xlApp.Quit()
VBA:
Public Sub test()
MsgBox "Hello World!"
End Sub
xlApp.Application.AutomationSecurity=1 needs to go before ANY xlApp.Application.Run(excelMacroNameHere) code, as the AutomationSecurity is used to control (enable vs disable) macros and 1 means enable all macros.
I'm writing a script to parse word document and get certain outputs. I use the following commands for reading the desired document.
import win32com.client as win32
import Tkinter,tkFileDialog
root = Tkinter.Tk()
root.withdraw()
filename = tkFileDialog.askopenfilename() # getting filename through windows explorer
word = win32.Dispatch("Word.Application")
#word.Documents.Open(filename)
The last line which is commented is how I was planning to implement this. But whenever I try to open a file which has a space in it's filename, this fails. In fact I found that if I give word.Documents.Open("C:/Python27/word sample.docm")
This will also fail, but if I use backslash after C: it'll work perfectly.
In short the below commands for opening document will work:
word.Documents.Open("C:\Python27/word sample.docm")
word.Documents.Open(filename) #if filename don't have a space
And the below ones will not work:
word.Documents.Open("C:/Python27/word sample.docm")
word.Documents.Open(filename) #filename have a space in it
Could someone explain what is going wrong here?
This is the error that I'm receiving:
C:\Users\xxx>C:\Python27\python.exe C:\Python27\test.py
Traceback (most recent call last):
File "C:\Python27\test.py", line 10, in <module>
word.Documents.Open("C:/Python27/word sample.docm")
File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Word'
, u'This file could not be found.\r (C:\\//Python27/word%20sample.docm)', u'
wdmain11.chm', 24654, -2146823114), None)