Search code examples
javascriptgoogle-sheets-apigoogle-sheets-macros

IF ELSE Loop problem in Google Sheets API


The code below pulls data from a small form, searches for a unique ID "uid" in a sheet "dbs" and copies new information into the correct line on the sheet. If am trying to finish the task by making it paste a new line to the bottom of the sheet if the person does not yet exist on the "dbs" sheet.

I have tried "if else" and "if", both looking for and not looking for "!== uid" and "".

(the copy to lines are // out for debugging only)

/** @OnlyCurrentDoc */
function submitData() {
  var ss = SpreadsheetApp.getActive();
  var static = ss.getSheetByName("Static Data"); //static data sheet
  var dbs = ss.getSheetByName("DBS Information"); //dbs sheet
  var menu = ss.getSheetByName("Menu");
  var uid = menu.getRange('E8').getValue();
  var values = dbs.getDataRange().getLastRow();


  // Logger.log(values)

  //find row number

  for (var i = 0; i < values.length; i++) {
    var row = "";
    for (var j = 0; j < values[i].length; j++) {

      if (values[i][j] == uid) {
        row = values[i][j];
        var x = 1;
        var z = x + i;
        Logger.log(z);
        // static.getRange("F2:M2").copyTo(dbs.getRange((z),1), {contentsOnly:true});
      } else {
        var R = dbs.getLastRow().getvalue;
        Logger.log(R);
        // static.getRange("F2:M2").copyTo(dbs.getRange((R),1), {contentsOnly:true});
      }
    }
  };
};

Solution

  • You could try setting a found variable if the uid is found, and then checking it after the loops to see whether to add a new row.

    /** @OnlyCurrentDoc */
    function submitData() {
        var ss = SpreadsheetApp.getActive();
        var static = ss.getSheetByName("Static Data"); //static data sheet
        var dbs = ss.getSheetByName("DBS Information"); //dbs sheet
        var menu = ss.getSheetByName("Menu");
        var uid = menu.getRange('E8').getValue();
        var values = dbs.getDataRange().getLastRow();
    
    
        // Logger.log(values)
    
        //find row number
    
        var found = false;
        for (var i = 0; i < values.length; i++) {
            var row = "";
            for (var j = 0; j < values[i].length; j++) {
    
                if (values[i][j] == uid) {
                    row = values[i][j];
                    var x = 1;
                    var z = x + i;
                    Logger.log(z);
                    found = true;
                    break;
                    // static.getRange("F2:M2").copyTo(dbs.getRange((z),1), {contentsOnly:true});
                }
            }
        };
    
        if (!found) {
            var R = dbs.getLastRow().getvalue;
            Logger.log(R);
            // static.getRange("F2:M2").copyTo(dbs.getRange((R),1), {contentsOnly:true});
        }
    };