Home > OS >  How to add string to next row in Google Sheet using Google Apps Script
How to add string to next row in Google Sheet using Google Apps Script

Time:11-03

I'm working on making a program from android studio to add string to google sheet. I'm using Google Script to input. I got stuck when trying to input a string to cell.

function addItem(e){
  var sheet =  ss.getSheetByName('items');
  var date = e.parameter.date;
  var lc = sheet.getLastColumn();
  var lr = sheet.getLastRow();
    
   for (var a = 2; a <= lr; a  ){
     var dd = sheet.getRange(a,1).getValue();
      if (dd == date){
       }
      if (dd != date){
       sheet.getRange(a 1, 1).setValue(date);
       }
   }
}

the first time I input it works as intended, but when I input for the second time (using a different date) instead of skipping and write, the first date just got replaced. I don't know what's wrong since if the second date is not same it should skip the first one right? What I encounter

CodePudding user response:

Probably it could be something like this:

function addItem(e) {
  ss.getSheetByName('items').appendRow([e.parameter.date]);
}

Update

Here is the expanded working example how it could be done if you need to skip repeated dates:

var ss = SpreadsheetApp.getActiveSpreadsheet();

function main() {
  var e = {parameter: {date : '123'}}; 
  addItem(e); // it will add a line

  e = {parameter: {date : '123'}}; 
  addItem(e); // it won't add a line, because the 'date' is the same

  e = {parameter: {date : '1234'}}; 
  addItem(e); // it will add a line again
}

function addItem(e) {
  var sheet = ss.getSheetByName('items');
  var data = sheet.getDataRange().getValues(); // get all data from the sheet
  var old_date = data.pop()[0];                // get first cell of last row of the data
  var new_date = e.parameter.date;             // new date
  if (old_date != new_date) sheet.appendRow([new_date]); // add a row if the dates aren't equal
}
  • Related