Search code examples
google-apps-scriptdelete-row

Copy and delete rows from one tab to another


I'm posting this message because I have a problem with my google script code.

I have two tabs in my sheet:

  • the first one is my database with all my records
  • the second one is an archive and should contain the data of the first tab I want to archive (where the checkbox is equal to true)

After checking some boxes, I run my script which must copy the lines where the boxes are checked in the archive tab and then delete this same line in the database tab. Everything works perfectly if I check only one box. However, when there are several selected, it does not delete the right ones.

Example:

row 1 and row 5 to be deleted → it deletes row 1 and row 4.

I ran a console.log to see where my error is coming from but I have to say I'm stuck. It must not be much but if someone has a few minutes to give me their opinion, I'm a taker.

Here is the link of my Sheet.

Thanks in advance for your feedback.

-- EDIT 1 --- Here is the code :

function archivage(){
   // Déclaration des constantes
   const classeur = SpreadsheetApp.getActiveSpreadsheet();
   const feuilleBDD = classeur.getSheetByName("bdd");
   const feuilleArchivage = classeur.getSheetByName("archive");

   // Récupération de l'ensemble des données
   var rangeDonnees = feuilleBDD.getRange("A2:D").getValues();

   // Récupération du nombre d'enregistrements
   var idEnregistrements = feuilleBDD.getRange("A2:A").getValues();
   var nbEnregistrements = idEnregistrements.filter(Number).length;

   for (let i =0; i < nbEnregistrements; i ++){
     // Récupération de la première ligne vide dans l'onglet "Archivage" et Création des coordonnées
     if (rangeDonnees[i][3]== true){
       var ligneVide = feuilleArchivage.getLastRow()+1;
       var coordLigneVide = "A"+ligneVide+":C"+ligneVide;
       var coordRangeACopier = "A"+ (2+i)+":C"+ (2+i);
       var coordDelete = 2 + i;
       // Récopiage des données dans l'onglet "Archivage"
       var range = feuilleBDD.getRange(coordRangeACopier);
       range.copyTo(feuilleArchivage.getRange(coordLigneVide));
       feuilleArchivage.getRange(coordLigneVide).setBackgroundRGB(255,255,255).setVerticalAlignment("middle").setHorizontalAlignment("center");
       Logger.log(coordDelete);
       feuilleBDD.deleteRow(coordDelete); 
     } else {
       continue;
     }
   }
 }

Solution

  • You need to keep track of the number of lines that you delete because as you delete lines the line numbers of the lines below it changes but the indices of the data does not so typically I use a delete counter like this:

    let startRow = "row where data starts";
    let d = 0;
    data.forEach((r,i)  => {
      if('conditional logic is in here to determine which lines') {
        sheet.deleteRow(i + startRow - d++);//the d++ deletes and then increments the delete counter after the operation
      }
    })