Home > Enterprise >  How to compare Sheet Names with Array elements and execute tasks on Google Sheets using script?
How to compare Sheet Names with Array elements and execute tasks on Google Sheets using script?

Time:10-22

The goal is to get each sheet name and check if it's not in the array. If not, then certain ranges are copied into a "database" sheet and then compare the next sheet and so on.

The problem is that itis comparing, it is giving me -1 as the result and it is executing the tasks, when it shouldn't be and I can't see where the flaw is.

Here's the code:

function concatenarResumos() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var databaseSheet = ss.getSheetByName("Database");
  var processedSheetsRng = ss.getSheetByName("Suporte").getRange("F6:F").getValues().flat();
  var shts = ss.getSheets();

  for (var j = 0; j < shts.length; j  ) {
    for (var n = 0; n < processedSheetsRng.length; n  ) {
      if (processedSheetsRng[n].indexOf(shts[j].getSheetName() === -1)) {

        shts[j].activate;
        var sheetName = shts[j].getSheetName();
        Logger.log("Sheet Name: "   sheetName);
        Logger.log("Processed Sheet Name: "   processedSheetsRng[n])

        var data = shts[j].getRange("C4").getValue();
        var naoConforme = shts[j].getRange("B8:G12").getValues();
        shts[j].getRange("B8:G12").copyTo(databaseSheet.getRange(databaseSheet.getLastRow()   1, 2, 6, naoConforme.length), { contentsOnly: true });

        var targetCol = databaseSheet.getRange('A:A').getValues();
        var maxIndex = targetCol.reduce(function (maxIndex, row, index) {
          return row[0] === "" ? maxIndex : index;
        }, 0);
        databaseSheet.getRange(maxIndex   2, 1, naoConforme.length, 1).setValue(data);
    }
  }
}

Here is the logger output: enter image description here

CodePudding user response:

function concatenarResumos() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const dsh = ss.getSheetByName("Database");
  const ssh = ss.getSheetByName("Suporte");
  const svs = ssh.getRange(6, 6, sh.getLastRow() - 5).getValues().flat();
  const shts = ss.getSheets();

  for (let j = 0; j < shts.length; j  ) {
    for (let n = 0; n < svs.length; n  ) {
      if (~svs[n].indexOf(shts[j].getName())) {
        let d1 = shts[j].getRange("C4").getValue();
        shts[j].getRange("B8:G12").copyTo(dsh.getRange(dsh.getLastRow()   1, 2, 6, d2.length), { contentsOnly: true });
        let tcol = dsh.getRange(1, 1, dsh.getLastRow()).getValues();
        let maxIndex = tcol.reduce(function (maxIndex, row, index) {return row[0] === "" ? maxIndex : index;}, 0);
        dsh.getRange(maxIndex   2, 1, d2.length, 1).setValue(d1);
      }
    }
  }

Ranges like F6:F & A:A are bad to use with google apps script because they create a lot of nulls at the end of the array which need to get filtered out.

  • Related