Search code examples
google-apps-script

Automatically adding a row to a sheet with data from another sheet once every day


I want to add a row to a sheet called "Historique" with data from another sheet called "Total" once every day

Historique sheet

(These are data written with my hand - data sent to the Total sheet in the graphic on the right,)

Date Total Banque Bourse Epargne salarié Crowdlending Crypto
01/01/2025 50000 20000 10000 10000 5000 5000
01/02/2025 65000 25000 5000 5000 10000 20000

Total sheet (datas sent to Historique sheet)

enter image description here

Script

function createTimeDrivenTriggers() {
    ScriptApp.newTrigger('storeValue')
        .timeBased()
        .everyDays(1)
        .create();
}

function storeValue() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName('Total');
    var total = sheet.getRange("B1").getValue();
    var banque = sheet.getRange("B3").getValue();
    var bourse = sheet.getRange("B4").getValue();
    var epargneSalarie = sheet.getRange("B5").getValue();
    var crowdlending = sheet.getRange("B6").getValue();
    var crypto = sheet.getRange("B7").getValue();

    var sheet2 = ss.getSheetByName('Historique');
    var height = sheet2.getLastRow();
    sheet2.insertRowAfter(height);
    sheet2.getRange(height + 1, 1, 1, 11).setValues([[new Date(), total, banque, bourse, epargneSalarie, crowdlending, crypto]]);
}

But I can't success to add automatically the rows with the script - it does nothing.


Solution

  • function storeValue() {
        var ss = SpreadsheetApp.getActiveSpreadsheet();
        var sheet = ss.getSheetByName('Total');
        const [[total],[],[banque],[bourse],[epargneSalarie],[crowdlending],[crypto]] = sheet.getRange("B1:B7").getValues();
        var sheet2 = ss.getSheetByName('Historique');
        var height = sheet2.getLastRow();
        sheet2.insertRowAfter(height);
        sheet2.getRange(height + 1, 1, 1, 7).setValues([[new Date(), total, banque, bourse, epargneSalarie, crowdlending, crypto]]);
    }