Add method of OLEObjects class failed - python

I'm trying to add an Excel Document within another Excel Document using OLEObjects in Python, but I'm getting this error:
d:\Python\PythonReport>d:/Python27/python.exe genDP.py d:/Python/PythonReport/ATP.xlsx
Traceback (most recent call last):
File "genDP.py", line 219, in <module>
add_ATP_WorkBook(OutputBook, sys.argv[1])
File "genDP.py", line 212, in add_ATP_WorkBook
oleObjects.Add(ClassType=None, Filename=file, Link=False, DisplayAsIcon=False, Left=0, Top=0, Width=50, Height=50)
File "<COMObject OLEObjects>", line 6, in Add
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel', u'Add method of OLEObjects class failed', u'C:\\Program Files (x86)\\Microsoft Office\\Office12\\1033\\XLMAIN11.CHM', 0, -2146827284), None)
What is strange is the fact that it works well for other files: I could easily add a text document as OLEObject, but when I try with an Excel Document I get that error.
This is the code:
def add_ATP_WorkBook(OutputBook, file):
ExcelApp = win32com.client.Dispatch("Excel.Application")
ExcelApp.visible = 1
workbook = ExcelApp.Workbooks.open(str(os.path.abspath(os.path.dirname(sys.argv[0])))+"\DVPR Report.xls")
oleObjects = workbook.ActiveSheet.OLEObjects()
oleObjects.Add(ClassType=None, Filename=file, Link=False, DisplayAsIcon=False, Left=0, Top=0, Width=50, Height=50)
workbook.Worksheets('Recognition Rate').Activate()

Related

Target specific Excel workbook by name with Python with win32com

If I have multiple Excel workbooks open on Windows 10, and I'm using win32com in Python, is there a way to choose a workbook by name? So far, I have been using:
ExcelApp = win32com.client.GetActiveObject('Excel.Application')
wb = ExcelApp.Workbooks(2)
but that requires the correct workbook to be the second one. Is there some way I can do it by name or filepath instead? I tried:
ExcelApp = win32com.client.GetActiveObject('Excel.Application')
wb = ExcelApp.Workbooks.Open(os.path.join(os.path.dirname(__file__), 'myworkbook.xlsm'))
but this does not work either if I have multiple Excel workbooks open. It ends up choosing the wrong workbook since later on, when it is looking for a specific sheet by name, it cannot find it.
If I try:
ExcelApp = win32com.client.GetActiveObject('Excel.Application')
wb = ExcelApp.Workbooks('My Workbook Name')
I get this:
Traceback (most recent call last):
File "E:\Archives\mypyscript.py", line 79, in <module>
wb = ExcelApp.Workbooks('My Workbook Name')
File "C:\Users\username\AppData\Local\Temp\gen_py\3.8\00020813-0000-0000-C000-000000000046x0x1x9\Workbooks.py", line 198, in __call__
ret = self._oleobj_.InvokeTypes(0, LCID, 2, (13, 0), ((12, 1),),Index
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)```

Trying to Send multiple emails by click of button using Tkinter with browsing file which has information of emails in python tkinter

I am trying to send multiple emails with click of button through tkinter, i have an excel file where i have written all my information (To-List,CC-List,Email-Subject,Email-Body) and saved in the folder.
Now i want to open the file through Browse button where it will look out for a file for that i created a function def input()
Then created another function def Email() for iterating the rows one by one and it will save the email in outlook.
I have created a below code where it has created three buttons:-
Browse Button - It will look out for file in which i have information for multiple emails
Begin Button - Email trigger
Quit Button - Close the application
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import win32com.client as win32
import pandas as pd
def input():
filename= filedialog.askopenfile()
def Email():
outlook = win32.Dispatch('outlook.application')
filterlist = pd.read_excel (input)
for index, row in filterlist.iterrows():
x1= row['ToEmail']
x2= row['CCEmail']
x3= row['Subject']
x4= row['Body']
mail = outlook.CreateItem(0)
mail.To = x1
mail.CC = x2
mail.Subject = x3
mail.Body = x4
mail.save()
master = tk.TK()
master.title('Email')
top_frame = tk.Frame(master)
bottom_frame= tk.Frame(master)
line = tk.Frame(master, height = 1, width = 400, relief = 'groove')
input_path = tk.Label(top_frame,text='Input File Path')
input_entry = tk. Entry (top_frame,text='', width = 40)
browse = tk.Button (top_frame, text="Browse", command = lambda : input())
begin_button = tk.Button (bottom_frame, text="Email Me!", command = Email)
quit_button = tk.Button (bottom_frame, text="Quit", command = master.destroy)
top_frame.pack(side=tk.TOP)
line.pack(pady=10)
bottom_frame.pack(side=tk.BOTTOM)
input_path.pack(pady=5)
input_entry.pack(pady=5)
browse.pack(pady=5)
begin_button.pack(pady=20,fill=tk.X)
quit_button.pack(pady=20,fill=tk.X)
master.mainloop()
When i am running this code i am getting the below error, its not reading the file correctly.
Can you please let me know what i am doing wrong.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\xxxx\anaconda3\lib\site-packages\win32com\client\dynamic.py", line 89, in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\xxxx\anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "<ipython-input-5-044b278bdd66>", line 12, in Email
outlook = win32.Dispatch('outlook.application')
File "C:\Users\xxxx\anaconda3\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "C:\Users\xxxx\anaconda3\lib\site-packages\win32com\client\dynamic.py", line 114, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:\Users\xxxx\anaconda3\lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)

xlwings error: not opening excel workbook getting an error upon call wb.open

xlwings works fine on my computer, but when I try to transfer the same set up to another computer it seems to not open correctly giving me this error
Traceback (most recent call last):
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 432, in __call__
return Book(xl=self.xl(name_or_index))
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 152, in __call__
v = self._inner(*args, **kwargs)
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\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, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\main.py", line 2776, in open
impl = self.impl(name)
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 434, in __call__
raise KeyError(name_or_index)
KeyError: 'output2019-06-03.11-40timeseries_5-31-2019scrubbed.xlsx'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Computation.py", line 157, in <module>
xwWb = xw.Book("output" + timeName + os.path.split(file_path)[1])
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\main.py", line 488, in __init__
impl = app.books.open(fullname).impl
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\main.py", line 2787, in open
impl = self.impl.open(fullname)
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 443, in open
return Book(xl=self.xl.Open(fullname))
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 63, in __call__
v = self.__method(*args, **kwargs)
File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Open method of Workbooks class failed', 'xlmain11.chm', 0, -2146827284), None)
Here is some simplified code where none of the data changing is occurring. Using ospath absolute does not help with the error. Both systems run the same 64 bit operating system and 32 bit excel. Yet the error persists on the second machine. There is no real difference I can understand that would give me an error on the 2nd system over the first one. Both machines are PCs
import xlrd
import openpyxl
import xlwings as xw
from xlwings import constants
import os
import tkinter as tk
from tkinter import filedialog
import datetime
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
print(file_path)
start = time.time()
wb = openpyxl.load_workbook(file_path)
Returns = wb['Prices']
newWs = wb.create_sheet()
newWs.title = "NominalDailyReturns"
benchWS = wb.create_sheet()
benchWS.title = "ActiveDailyReturns"
thirdWs = wb.create_sheet()
thirdWs.title = "RawAnalysis"
thirdWs.column_dimensions["A"].width = 32
name4 = thirdWs.title
print("halfway")
print(os.path.split(file_path))
print("output" + timeName + os.path.split(file_path)[1])
wb.save("output" + timeName + os.path.split(file_path)[1])
xwWb = xw.Book(os.path.abspath("output" + timeName + os.path.split(file_path)[1]))
XnewWs = xwWb.sheets['NominalDailyReturns']
xwWb.save()
xwWb.close()
wb = openpyxl.load_workbook("output" + timeName + os.path.split(file_path)[1])
benchWS = wb['ActiveDailyReturns']
wb.save("output" + timeName + os.path.split(file_path)[1])
xwWb = xw.Book("output" + timeName + os.path.split(file_path)[1])
XthirdWs = xwWb.sheets['RawAnalysis']
xwWb.save()
xwWb.close()
I figured out the problem with my code. When I used openpyxl to edit my excel data, one of the formulas was subtracting a word from a number, raising an error and corrupting the excel file. Then xlwings tried to open a corrupted file, and it failed on me.
So the solution is to not save a corrupted excel file and expect xlwings to open it.

MDB/ACCDB execute macro/function (with parameters) by python script

I want to execute a macro/function code with python script. I have this code example:
from win32com.client import Dispatch
objAccess = Dispatch("Access.Application")
objAccess.Visible = False
objAccess.OpenCurrentDatabase(strDbName)
objDB = objAccess.CurrentDb()
objAccess.DoCmd.RunMacro('MyMacro')
objAccess.Application.CloseCurrentDatabase()
objAccess.Application.Quit()
del objAccess
del objDB
But I get this error:
Traceback (most recent call last):
File "D:\workspace-python\TOOLS\SHPTOOL\test.py", line 8, in <module>
objAccess.DoCmd.RunMacro('MyMacro')
File "<COMObject <unknown>>", line 3, in RunMacro
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, u"Microsoft Office Access can't find the object 'MyMacro.'", u'ACMAIN11.CHM', 10183, -2146825803), None)
Then I try another approach, call RUN method:
objAccess = Dispatch("Access.Application")
objAccess.Visible = False
objAccess.OpenCurrentDatabase(strDbName)
objDB = objAccess.CurrentDb()
objAccess.Run('merge', "mystringparameter")
objAccess.Application.Quit()
error:
Traceback (most recent call last):
File "D:\workspace-python\TOOLS\SHPTOOL\test.py", line 58, in <module> objAccess.Run('merge', "mystringparameter")
File "<COMObject Access.Application>", line 14, in Run
File "C:\Python27\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, None, u"Microsoft Office Access can't find the procedure 'merge.'", None, -1, -2146825771), None)
And my MDB code, the 3 functions:
Sub merge(path As String)
MsgBox "Inside generated macro!!! " & path
End Sub
Sub MyMacro()
MsgBox "Inside generated macro!!!"
End Sub
Function MyFunction()
MsgBox "You MUST select a Destination Folder!"
End Function
Thanks
Just replace
objAccess.DoCmd.RunMacro('MyMacro')
by
objAccess.run('MyMacro')
\o/

win32api.FormatMessage() error

I am trying to get a named Range in code like this:
Range(rng_name, index=False).value = df_grouped_a.ix[loc][col]
This generates exception:
File "C:/Users/acme/python/s.py", line 149, in <module>
Range(rng_name, index=False).value = df_grouped_a.ix[loc][col]
File "C:\Program Files (x86)\Python271\lib\site-packages\xlwings\main.py", line 620, in __init__
self.row1 = xlplatform.get_first_row(self.xl_sheet, range_address)
File "C:\Program Files (x86)\Python271\lib\site-packages\xlwings\_xlwindows.py", line 122, in get_first_row
return xl_sheet.Range(range_address).Row
File "<COMObject <unknown>>", line 3, in Range
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None)
It might be related to the named range issue, but I would like to get the meaning of error code -2146827284 first.
Unfortunately, the way described here does not work for me: https://stackoverflow.com/a/36080159
Namely:
>>> import win32api
>>> win32api.FormatMessage(-2146827284)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pywintypes.error: (15100, 'FormatMessage', 'The resource loader failed to find MUI file.')
How can I find the error message corresponding to this error code?
-2146827284 may be represented as 0x80020009‬, is a COM Error Code. That mean DISP_E_EXCEPTION - Basic value returned if COM exception ooccured.
Simpliest way to 'convert' singed int to unsigned is to apply bitwise & 0xFFFFFFFF operation.
>>> error = -2146827284
>>> error & 0xffffffff
‭2147614729‬
But nothing special you will see when try to
>>> win32api.FormatMessage(error)
Exception occurred.

Categories