Home > Back-end >  How to refresh and add value a cell in Google sheet using Google Apps Script at same time
How to refresh and add value a cell in Google sheet using Google Apps Script at same time

Time:11-09

I tried to input 2 values in 1 function. I can input first one without problem, the second one is being inputted based on the first value, so since both of them in same function the second one can't be inputted. I tried to use flush() method after I inputted first value, but the second value still cant find the first value. Here's my code :

function addItem(e){
   var sheet =  ss.getSheetByName('items');
    var id = e.parameter.id; 
    var qty = e.parameter.qty;
    var lc = sheet.getLastColumn();
    var lr = sheet.getLastRow();
    var data = sheet.getDataRange().getValues();
    var old_date = data.pop()[0];
    var new_date = e.parameter.date;
    if (old_date != new_date) sheet.appendRow([new_date]);
    
    SpreadsheetApp.flush();

    for (var i = 1; i <= lc; i  )  {
      for (var j = 1; j <= lr; j  ) {
        var rid = sheet.getRange(1, i).getValue();
        var red = sheet.getRange(j,1).getValue();
        if (rid == id && red == new_date){
            sheet.getRange(j, i).setValue(qty);
        }}}}

My goal is to add string new_date by using pop()[0] and appendRow, wait for the data is inputted using SpreadsheetApp.flush(), getting both Range and Value of new_dateand id with increment checking all rows and column, so I can input qty based on id column and new_date row.

as you can see in the picture, the new_date 11/11/1111 is in (row 3, column 1) meanwhile the id 1 is in (row 1,column 2), and I need to input qty in (row 3 and column 2). the problem that I have is when the code is running, it can't detect the new_date that just being inputted, so the qty can't be inputted because it think that the new_date is not there.

What I encounter

CodePudding user response:

I just separate the function and it works perfectly.

function addDate(e){
    var sheet =  ss.getSheetByName('items');
    var data = sheet.getDataRange().getValues();
    var old_date = data.pop()[0];
    var new_date = e.parameter.date;
    if (old_date != new_date) sheet.appendRow([new_date]);
}

function addItem(e){
    var sheet =  ss.getSheetByName('items');
    var sku = e.parameter.sku;
    var qty = e.parameter.qty;
    var date = e.parameter.date;
    var lc = sheet.getLastColumn();
    var lr = sheet.getLastRow();
    SpreadsheetApp.flush();
    for (var i = 1; i <= lc; i  )  {
        for (var j = 1; j <= lr; j  ) {
            var rid = sheet.getRange(1, i).getValue();
            var red = sheet.getRange(j,1).getValue();
            if (rid == sku && red == date){
                sheet.getRange(j, i).setValue(qty);
                var result = "Input Succeed";
            }
        }
    }
}
  • Related