Google Sheets – Copying Last Row to Another Spreadsheet on Form Submission

google sheetsgoogle-apps-script

I would like to copy lastRows from 'Source1' sheet to 'Destination1' sheet. Triggers are on every change form 'Source1'.

The code below can help me to do the job.

function copyLastRow() {  
var target = SpreadsheetApp.openById('xxxxx-keyfile').getSheetByName('Destination1'); // copy data into this file & sheet.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Source1'); // name of source sheet. 
var lastrow = sheet.getLastRow();
var sourceData = sheet.getRange(lastrow, 1,1, 37).getValues();
target.appendRow(sourceData[0]);}

I also set up another function as below. This function is for automatically clearing data from 'source 1' on specify time (e.g: everyday at 1 am).

function clearRange() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Source1');
sheet.getRange('A2:F').clearContent();}

When function clearRange() run at 1 am on everyday, data on 'source1' with range A2:F will be clear. At that moment, the range 'A1:F1' will be as the LastRow and it will be copied to 'Destination1' as the copyLastRow() function is still running.

What I would do is the copyLastRow() function don't copy the range A1:F1 as the LastRow.

I'm quite new in not only GAS but also JS…so I would appreciate if anyone could understand and help me to solve my problem.

The mentioned code above was copied from this post.

Best Answer

Just check to see if the first item in the sourceData Array is not the same value that is in A1 before you copy the data over. I am assuming this is a title row and that you don't have anyone named "name" in your data set.

var sourceData = sheet.getRange(lastrow, 1,1, 37).getValues();
if (sourceData[0][0] != sheet.getRange(1, 1).getValue();){
  target.appendRow(sourceData[0]);
  }
}