I am trying to execute a macro through python script. When I run it first time it runs properly, but when I run it again after few minutes, it throws error as
File "<COMObject <unknown>>", line 2, in run pywintypes.com_error:
(-2147352567, 'Exception occurred.', (0, None, None, None, 0,
-2146827284), None)
My script:
import win32com.client as win32
import time
excel=win32.Dispatch("Excel.Application")
excel.visible=1
book=excel.Workbooks.open('C:\\Users\\C296442\\Documents\Application07012020.xlsm')
excel.application.run("Application07012020.xlsm!Sheet5.CommandButton12_Click")
I have found 2 ways to do this and both seem to work fine.
from __future__ import print_function
import unittest
import os.path
import win32com.client
class ExcelMacro(unittest.TestCase):
def test_excel_macro(self):
try:
xlApp = win32com.client.DispatchEx('Excel.Application')
xlsPath = os.path.expanduser('C:\\Users\\rshuell001\\Desktop\\Valuation Code Rollover.xlsb')
wb = xlApp.Workbooks.Open(Filename=xlsPath)
xlApp.Run('Macro1')
wb.Save()
xlApp.Quit()
print("Macro ran successfully!")
except:
print("Error found while running the excel macro!")
xlApp.Quit()
if __name__ == "__main__":
unittest.main()
import os
import win32com.client
#Launch Excel and Open Wrkbook
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm") #opens workbook in readonly mode.
#Run Macro
xl.Application.Run("excelsheet.xlsm!modulename.macroname")
#Save Document and Quit.
xl.Application.Save()
xl.Application.Quit()
#Cleanup the com reference.
del xl
Related
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")
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
When I run macro in Excel, the code executes completely. But the code is not completely done when I try to run macro using Python.
In the VBA code, I used this code to ignore all error triangles in each cell so the file created did not include these errors(image below).
enter image description here
But when I try to use macro in Python. The triangle errors occur, and I don't know why (Python code).
import os
import win32com.client as wincl
def runMacro(file_path):
if os.path.exists(file_path):
excel_macro = wincl.DispatchEx("Excel.Application")
workbook = excel_macro.Workbooks.Open(file_path)#,None,False)
try:
excel_macro.Application.Run("module1.create_WP")
workbook.Save()
except Exception as ex:
print(ex)
finally:
excel_macro.Application.Quit()
del excel_macro
path = "D:\OneDrive - Central Group\Khôi\Weekly performance\Original files\TOTAL2022(UPDT.).xlsm"
runMacro(path).
The triangle errors occur enter image description here
Can you try it this way and feed back results?
from __future__ import print_function
import unittest
import os.path
import win32com.client
class ExcelMacro(unittest.TestCase):
def test_excel_macro(self):
try:
xlApp = win32com.client.DispatchEx('Excel.Application')
xlsPath = os.path.expanduser('C:\\Excel.xlsb')
wb = xlApp.Workbooks.Open(Filename=xlsPath)
xlApp.Run('Macro1')
wb.Save()
xlApp.Quit()
print("Macro ran successfully!")
except:
print("Error found while running the excel macro!")
xlApp.Quit()
if __name__ == "__main__":
unittest.main()
I am getting the below error while running the given code from Azure devops pipeline and the same code works fine when triggered from local virtual machine. Any help would be indeed appreciated!!!
Error:
com_error: (-2147221005, 'Invalid class string', None, None)
Versions:
pywin32 = 300,
Excel = WPS Office
Agent Type: Self hosted agent configured in C: drive which is running as a service.
from threading import Lock
import win32com.client as win32
from openpyxl import load_workbook
from pyexcelerate import Workbook, Color, Style, Fill
from win32com.client import Dispatch, DispatchEx
from xlrd import open_workbook
with lock:
while True:
try:
EP._filepath = filepath
EP._activesheet = open_workbook(filepath)
break
except:
ValueError
try:
xl = Dispatch('Excel.Application')
except:
xl = DispatchEx('Excel.Application')
finally:
xl = win32.gencache.EnsureDispatch('Excel.Application')
wb = xl.Workbooks.Open(filepath)
wb.Close(True)
The code for python works except that once it has ran I still get a box from excel asking "want to save your changes to workbook" what I seem to be missing in my code is to add something that will SAVE the workbook at the very end. I use RTD functions in the workbook which might be the reason the popup.
This is my python code used.
from __future__ import print_function
import unittest
import os.path
import win32com.client
class ExcelMacro(unittest.TestCase):
def test_excel_macro(self):
try:
xlApp = win32com.client.DispatchEx('Excel.Application')
xlsPath = os.path.expanduser('C:\Magic Samsung\Watch Samsung\Workbook.xlsm')
wb = xlApp.Workbooks.Open(Filename=xlsPath)
xlApp.Run('ArchiveMaster')
wb.Save()
xlApp.Quit()
print("Macro ran successfully!")
except:
print("Error found while running the excel macro!")
xlApp.Quit()
if __name__ == "__main__":
unittest.main()
according to this Link xlOpenXMLWorkbookMacroEnabled is 52. so, while saving just give the argument FileFormat = 52 as shown in the below code
class ExcelMacro(unittest.TestCase):
def test_excel_macro(self):
try:
xlApp = win32com.client.DispatchEx('Excel.Application')
xlapp.DisplayAlerts=False
xlsPath = os.path.expanduser('C:\Magic Samsung\Watch Samsung\Workbook.xlsm')
wb = xlApp.Workbooks.Open(Filename=xlsPath)
xlApp.Run('ArchiveMaster')
wb.SaveAs(Filename=path_here, FileFormat=52)
xlApp.Quit()
print("Macro ran successfully!")
except:
print("Error found while running the excel macro!")
xlApp.Quit()
if __name__ == "__main__":
unittest.main()
Note: A pop-up appear's while using saveAs. This SO question and This So
Post answer's this problem
I am trying to use python to run an excel macro and then close excel. I have the following:
import win32com.client
import os
xl = win32com.client.DispatchEx("Excel.Application")
wb = xl.workbooks.open("X:\Location\Location2\File1.xlsm")
xl.run("File1.xlsm!WorkingFull")
xl.Visible = True
wb.Close(SaveChanges=1)
xl.Quit
My script will Open and close fine if I take out the xl.run("File1.xlsm!WorkingFull")
When I run this I get the following error:
Traceback (most recent call last):
File "C:\Python27\File1.py", line 6, in
xl.run("File1.xlsm!WorkingFull")
File "", line 2, in run
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'File1.xlsm!WorkingFull'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
I have macros enabled and I know its in the workbook, what is the problem?
please see below the code for running an Excel macro using python. You can find this code in this Site - Link. Use this site for other references for excel, vba and python scripts which might be helpful in the future.
from __future__ import print_function
import unittest
import os.path
import win32com.client
class ExcelMacro(unittest.TestCase):
def test_excel_macro(self):
try:
xlApp = win32com.client.DispatchEx('Excel.Application')
xlsPath = os.path.expanduser('C:\test1\test2\test3\test4\MacroFile.xlsm')
wb = xlApp.Workbooks.Open(Filename=xlsPath)
xlApp.Run('macroName')
wb.Save()
xlApp.Quit()
print("Macro ran successfully!")
except:
print("Error found while running the excel macro!")
xlApp.Quit()
if __name__ == "__main__":
unittest.main()