Error handling for Macro calling using python - python

I am using python to run excel macros but the problem I am getting is that an error is popping up when I run the macros.
How can hide this error pop up?
Following are the piece of code :
try:
if os.path.exists("C:\\test.xlsm"):
# DispatchEx is required in the newest versions of Python.
excel_macro = win32com.client.DispatchEx("Excel.application")
excel_path = os.path.expanduser("C:\\test.xlsm")
workbook = excel_macro.Workbooks.Open(Filename=excel_path,ReadOnly=1)
excel_macro.Application.DisplayAlerts = False
excel_macro.Application.Run("Macro1")
# Save the results in case you have generated data
workbook.Save()
excel_macro.Application.Quit()
del excel_macro
except:
print("Error found while running the excel macro!")
excel_macro.Application.Quit()

Related

'INFO: Could not find files for the given patterns' Error I receive using pdfkit

I convert .csv file to HTML and then try to convert HTML to PDF using pdfkit... What am I doing wrong. How do I fix this. Here is my code snippet below.
import pdfkit
# put unsafe operation in try block
try:
print("code start")
# unsafe operation perform
# wkhtmltopdf = WKHtmlToPdf(url='pypi.org', output_file='new.pdf')
pdfkit.from_file('myhtml.html', 'mypdf.pdf')
# pdfkit.from_url('https://www.google.com/', 'mypdf.pdf')
print(1 / 4)
# if error occur the it goes in except block
except:
print("an error occurs")
# final code in finally block
finally:
print("StackOverFlow")
I do not have wkhtmltopdf imported, is that a mistake
Install the GTK runtime from this link: https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer/releases
Then in your code add:
import os
os.add_dll_directory(r"C:\Program Files\GTK3-Runtime Win64\bin")

python 'bool' object is not callable'

I have seen a few other similar questions, unfortunately none quite solved my issue. my codes are pretty extensive so not going to paste everything here. my python script is running an excel and a macro within. its does all the fine but when it comes to saving the file down I get the error. I have shown snippets of my codes below. any idea what seems to be happening? it sporadically works well and randomly stops working.
import win32com.client
import time
from datetime import datetime
def openWorkbook(xlapp, xlfile,upDateLink,openReadOnly,wbVisible):
try:
xlwb = xlapp.Workbooks(xlfile,upDateLink,openReadOnly,wbVisible) # the 2nd is for updatelink, 3rd is for OpenReadOnly
except Exception as e:
try:
print('run function')
xlapp.Workbooks.Open('C:\\blp\\API\\Office Tools\\BloombergUI.xla')
xlapp.RegisterXLL('C:/blp/API/Office Tools/bofaddin.dll')
xlwb = xlapp.Workbooks.Open(xlfile,upDateLink,openReadOnly) # the 2nd is for updatelink, 3rd is for OpenReadOnly
xlapp.Visible = wbVisible
except Exception as e:
print(e)
xlwb = None
return(xlwb)
wb1 = openWorkbook(xlapp, filepath,False,True,wbVisible)
filepathSaveStress = "C:\\Users\\abc\\Downloads\\Projects\\Stress" + extractDate2 + ".xlsm"
print('run CalculateValues')
xlapp.Application.run("CalculateValues")
xlapp.DisplayAlerts = False
if stresstype == 'Stress':
wb1.SaveAs(filepathSaveStress)
else:
wb1.SaveAs(filepathSavePostStress)
not sure why it errors out at wb1.SaveAs(filepathSaveStress)
in term or error all I get is this
'bool' object is not callable

Why is 'invalid length' error message showing when using Oracle_cx?

Using cx_Oracle, I am trying to use a Python script to execute a sql command, using the bind variables 'plat' and 'tick'. When trying to execute this command, it gives me the error "ORA-24373: invalid length specified for statement".
To debug, I made a SQL call through Oracle (not Python) using the same arguments as my script (plat=1234567, tick='ABCDE'), and it ran as expected. I tried passing the parameters as both a dict and individual named variables, but both times I got the same error.
I tried changing the values to be lower ('1' and 'A'), but even that is an 'invalid length'.
updateRecords.py
import os
import cx_Oracle
# For security reasons I cannot show my 'create_connection()' function,
# but suffice to say I have tested it and it works as desired.
...
#Setup:
WORKING_PATH = os.path.dirname(os.path.abspath(__file__))
SQL_PATH = os.path.join(WORKING_PATH, 'sql')
cnnSB = create_connection()
cnnSB_cursor = cnnSB.cursor()
...
fetchComp = open(os.path.join(SQL_PATH, 'fetchRecentEntry.sql'), 'r')
for x in range(0, 5):
cnnSB_cursor.execute(fetchComp.read(), {"plat":'A', "tick":1}) # ERROR LINE
fetchRecentEntry.sql
select *
from MFS_PCIINCEXTFUNDBYPLAT
where PLATFORM = :plat
and TICKER = :tick
and STARTDATE = (select max(STARTDATE) from MFS_PCIINCEXTFUNDBYPLAT
where PLATFORM = :plat
and TICKER = :tick)
The above snippet results in the following error message:
File "updateRecords.py", line 297, in main
cnnSB_cursor.execute(fetchComp.read(), plat='A', tick=1)
cx_Oracle.DatabaseError: ORA-24373: invalid length specified for statement
Other things I have checked:
-My fetchComp.read() DOES return the desired code
-Passing in variables as a dict object does NOT change the error message
I found a solution:
The issue comes from the .read() being called inside of a loop. As a result, it would read the file correctly the first time, but on subsequent loops it would only read the null/EOF.
To fix, all I had to do was set the sql.read() to a variable before the loop, and use that variable instead of calling .read() with each loop.
Example:
sql = fetchComp.read()
for index, testRow in testDF.iterrows():
cnnSB_cursor.execute(sql, tick=testRow[1], plat=testRow[0])
compDF = pd.DataFrame(cnnSB_cursor.fetchall())

Error in deleting excel sheet after exporting using python

I am trying to save the chart from Excel as an image file in Python. I am using WIn32com, the chart is getting exported as required but when I am trying to delete the ActiveSheet,it is giving me the error.
excel.ActiveSheet().Delete()
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in __call__
return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
pywintypes.com_error: (-2147352573, 'Member not found.', None, None)
Any help to overcome this error?
Below is my code:
import win32com.client as win32
def saveChart():
excel = win32.Dispatch("Excel.Application")
wb = excel.Workbooks.Open(r'C:\Users\projects\Rating.xlsx')
selection = "A1:K16"
xl_range = wb.Sheets("Categories").Range(selection)
excel.ActiveWorkbook.Sheets.Add().Name="image_sheet"
cht = excel.ActiveSheet.ChartObjects().Add(0,0,xl_range.Width, xl_range.Height)
xl_range.CopyPicture()
cht.Chart.Paste()
cht.Chart.Export(r'C:\Users\projects\MyExportedChart.png')
excel.DisplayAlerts = False
cht.Delete()
excel.ActiveSheet.Delete()
excel.DisplayAlerts = True
excel.ActiveWorkbook.Close()
I took the code from Export Charts from Excel as images using Python
Updated the code,which worked
Is ActiveSheet a field, like you're using it here:
cht = excel.ActiveSheet.ChartObjects().Add(0,0,xl_range.Width, xl_range.Height)
Or a method like you're using it here:
excel.ActiveSheet().Delete()
Since the first call doesn't give you the error, and the error says that the member is not found, I'm going to guess that the second one is wrong, and should be:
excel.ActiveSheet.Delete()

Automation Excel From Python getting "TypeError: 'unicode' object is not callable" on Range.Address

As per the Title, when I run the below code in Python 2.6 I get the below error on line:
print range.Address(RowAbsolute=False,
ColumnAbsolute=False)"
I know what the error means but the MSDN page (http://msdn.microsoft.com/en-us/library/aa174749(v=office.11).aspx) said this is valid and has an example in it. I have tried this in EXCEL VBA and it works.
TypeError: 'unicode' object is not
callable
Any ideas?
Thanks.
Doanld
import win32com.client
xlApp = win32com.client.DispatchEx('Excel.Application')
xlApp.Visible = True
objWkb = xlApp.Workbooks.Add()
objSht = objWkb.Worksheets(1)
objSht.Cells(2,2).Value = '1'
objSht.Cells(2,3).Value = '2'
range = objSht.Cells(2,4)
range.Value = '=%s+%s' % (objSht.Cells(2,2).Address, objSht.Cells(2,3).Address)
range.AddComment('Test Comment')
print range.Address
print range.Address(RowAbsolute=False, ColumnAbsolute=False)
objWkb.Close(SaveChanges=False) #to avoid prompt
xlApp.Quit()
xlApp.Visible = 0 #must make Visible=0 before del self.excelapp or EXCEL.EXE remains in memory.
del xlApp
Range.Address is a parameterized property. It provides a value when accessed like a property, but can be called like a method with parameters as well. PyWin32 does not support parameterized properties directly. It works around this by providing a GetXXXXX method for each property that supports parameters. Use:
range.GetAddress(RowAbsolute=False,ColumnAbsolute=False)
It can be used with or without keywords.
Use either:
range.GetAddress()
range.Address
To read the property.

Categories