jkpieterse
jkpieterse

Reputation: 2986

Getting the sourceString of all pivot tables in a workbook

I'm trying to run through all pivottables in an Excel workbook and list their sources, but I'm not succeeding. I'm using code like this:

async function SearchInPivots(
  context, wb: Excel.Workbook) {
  let foundPivots = new foundCollection();
  let pts = wb.pivotTables.load("items");
  let ptCt = pts.getCount();
  await context.sync();
  let ptColl = [];
  let pt:Excel.PivotTable = null;
  for (let i: number = 0; i < ptCt.value; i++) {
    pt = pts[i].load("getDataSourceString");
    ptColl.push(pt);
  }
  await context.sync();

  for (let i: number = 0; i < ptColl.length; i++) {
    console.log(ptColl[i].getDataSourceString());
  }
  return foundPivots;
}

WHat is wrong with my code?

Upvotes: 0

Views: 80

Answers (1)

Jakob Nielsen-MSFT
Jakob Nielsen-MSFT

Reputation: 514

Try this code instead:

await Excel.run(async(context) => {

  // Get the PivotTables in the workbook
  const pivotTables = context.workbook.pivotTables.load("items");
  await context.sync();

  // Get the data sources for each PivotTable
  const dataSources = [];
  pivotTables.items.forEach((pivotTable) => {
    dataSources.push(
      pivotTable.getDataSourceString()
    );
  });
  await context.sync();

  dataSources.forEach((dataSource) => {
    console.log(dataSource.value);
  });
});

Here is the code in a Script Lab snippet

Upvotes: 2

Related Questions