title: How to add Calculated Member to Pivot Table via Python win32
body: <p>I'm trying to add a calculated column into this pivot table that is being generated via a python script with <code>import win32com.client</code>.</p>
  
  <p>Code is posted below that is generating the pivot table. I'm not sure how to add a column. In VBA it would be <code>wb.PivotTable.CalculatedField.Add</code> but that didn't work (at least the syntax I tried).</p>
  
  <p>I'm trying to calculate <code>[OoCUnits] / [GrossUnits]</code></p>
  
  <pre><code>#Make Pivot version with four weeks data
  Excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
  win32c = win32com.client.constants
  wb = Excel.Workbooks.Open(filename)
  ws3 = wb.Worksheets('Dataset')
  
  cl1 = ws3.Cells(1,1)
  cl2 = ws3.Cells(max_row,max_col)
  PivotSourceRange = ws3.Range(cl1,cl2)
  ws3.Activate()
  PivotSourceRange.Select()
  wb.Sheets.Add (After=wb.Sheets(3))
  ws4 = wb.Worksheets(4)
  ws4.Name = 'Pivot'
  
  cl3 = ws4.Cells(4,1)
  PivotTargetRange = ws4.Range(cl3,cl3)
  PivotTableName = 'OoCPivot'
  
  #Make Pivot Table
  PivotCache = wb.PivotCaches().Create(SourceType=win32c.xlDatabase, SourceData=PivotSourceRange, Version=win32c.xlPivotTableVersion14)
  PivotTable = PivotCache.CreatePivotTable(TableDestination=PivotTargetRange, TableName=PivotTableName, DefaultVersion=win32c.xlPivotTableVersion14)
  
  PivotTable.PivotFields('Product Name').Orientation = win32c.xlRowField
  PivotTable.PivotFields('Product Name').Position = 1
  PivotTable.PivotFields('Customer Number').Orientation = win32c.xlPageField
  PivotTable.PivotFields('Customer Number').Position = 1
  PivotTable.PivotFields('Customer Name').Orientation = win32c.xlPageField
  PivotTable.PivotFields('Customer Name').Position = 2
  PivotTable.PivotFields('Week Ending Date').Orientation = win32c.xlColumnField
  PivotTable.PivotFields('Week Ending Date').Position = 1
  DataField = PivotTable.AddDataField(PivotTable.PivotFields('GrossUnits'))
  DataField.NumberFormat = '#0.00'
  DataField = PivotTable.AddDataField(PivotTable.PivotFields('OoCUnits'))
  DataField.NumberFormat = '#0.00'
  </code></pre>
  
  <p>I'm inserting the values with the <code>DataField</code>. The script is not presenting any issues as is.</p>
  
  <p>EDIT: The exact code I implemented to solve. The last two lines are just formatting. I'm including in case it helps someone else.</p>
  
  <pre><code>CalcField = PivotTable.CalculatedFields().Add('OoC Unit %','= OoCUnits / GrossUnits')
  DataField = PivotTable.AddDataField(PivotTable.PivotFields('OoC Unit %'))
  DataField.NumberFormat = '#%'
  PivotTable.DisplayErrorString = True
  </code></pre>