Como criar uma string a partir dos nomes das planilhas usando scripts do Google App?

Oct 03 2020

Estou tentando criar uma string adicionando todos os nomes de folha (tendo alfabetos e números em seus nomes). A string exata que preciso gerar está começando de = QUERY a 0), onde PHY4101, MATH4103, HUM4105, ICTE4115 etc. vêm dos nomes das folhas de uma planilha. Finalmente, a string será definida como um valor para a célula A2 da Masterfolha. Como corrigi-lo?

A string exata a produzir: = QUERY ({PHY4101! A2: F; MATH4103! A2: F; HUM4105! A2: F; ICTE4115! A2: F; ICTE4117! A2: F; ICTE4143! A2: F; PHY4102! A2: F; HUM4106! A2: F; ICTE4144! A2: F}, "selecione * onde Col3 não é nulo", 0)

function formatSheetsP3() {
  var sss = SpreadsheetApp.getActiveSpreadsheet();
  
  const allsheets = sss.getSheets().filter(sh => /\d/.test(sh.getName()));    
  for(var s in allsheets){
    var sheet = allsheets[s].getName();
    var str = '=QUERY({'+ sheet + '!A2:F;'
  } 
  str2 = str + '},"select * where Col3 is not null",0)';
  var master = sss.getSheetByName("Master");
  master.getRange("A2").setValue(str2);
}

Respostas

2 Mario Oct 03 2020 at 01:26

Você pode simplificar seu código ainda mais.

Aqui está a solução:

function formatSheetsP3() {
  let sss = SpreadsheetApp.getActiveSpreadsheet();
  let allsheets = sss.getSheets().filter(sh => /\d/.test(sh.getName())).map(n=>n.getName());
  let mid ='';    
  allsheets.forEach((sh,index)=>{
     let temp = index>0 ? `;${sh}!A2:F`:`${sh}!A2:F`;
     mid+=temp;
  })
  let str2 = `=QUERY({${mid}},"select * where Col3 is not null",0)`
  let master = sss.getSheetByName("Master");
  master.getRange("A2").setValue(str2); 
}
3 TheMaster Oct 03 2020 at 01:31

Mapeie, filtre e junte:

const formula = `=QUERY({${sss .getSheets() .map(sh => `${sh.getName()}!A2:F`)
  .filter(sh => /\d\!A2:F$/.test(sh))
  .join(';')}},"select * where Col3 is not null",0)`;