I'm trying to refresh a pivot table in excel and update existing filters using python's win32com. However, I'm hitting the error of:
com_error: (-214735267, 'Exception occured.', (0, 'Microsoft Excel', 'PivotFields method of PivotTable class failed', 'xlmain11.chm', 0, -2146827284), None)
Here's my code:
import win32com.client
filepath = r'test.xlsx'
office = win32com.client.Dispatch('Excel.Application')
office.DisplayAlerts = False
wb = office.Workbooks.Open(filepath, False, False, None)
ws = wb.Worksheets[0]
for i in range(1,3):
ws.PivotTables(i).PivotCache().Refresh()
ws.PivotTables(1).PivotFields('Position_date').PivotFilters.Add2(34, None, '31/05/2021')
# 34 = xlAfterorEqualTo
wb.SaveAs(filepath, None, '', '')
office.Quit()
Appreciate any help I can get on this. Thanks.
ws=wb.Worksheets[0]worked fine. Then I updated pywin32 to 301 (from 300), and replaced the application object creation line withoffice=win32com.client.gencache.EnsureDispatch('Excel.Application'). Once I did this, thenWorksheets[0]failed: it now needed to beWorksheets[1]orWorksheets(1). Go figure. I switched back towin32com.client.Dispatch('Excel.Application')but still needed the 1-based worksheet index. One by-product was that I could now accesswin32com.client.constants.xlAfterOrEqualToinstead of using 34.Position_dateis the right name. I get this error if I ask for a name that doesn't exist. The names aren't case-sensitive in my experience. Perhaps iterate through the PivotFields collection, and print out each Name, just to check.ws.PivotTables(2).PivotFields('Position_date').PivotFilters.Add(34, None, '31/05/2021'However, I'm still getting the com_error. I'm using Add instead of Add2 as I'm using an old version which doesn't have Add2. Any idea on the com_error issue?pvt = ws.PivotTables(2)thenflds = pvt.PivotFields(),fld = flds('Position_date')etc rather than chain all the function calls together. Check each variable along the way (eg checkflds.Count).