How to copy the last cell from the specific Column

32 views
Skip to first unread message

Excel Google

unread,
Nov 23, 2021, 10:33:51 AM11/23/21
to Google Apps Script Community

I have been trying to copy the last non empty cell from Sheet1 Column A and paste that cell into the last empty cell of the Sheet2 Column D.

that code should work whenever Sheet1 ColA is edited or update new value.

But an error The coordinates of the target range are outside the dimensions of the sheet. is appearing. Any help will be appreciated.


function myFunction() {

  const sheetName1 = "sheet1";

  const sheetName2 = "sheet2";

  const sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName1);

  const sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName2);

  const lastRow1 = sheet1.getLastRow();

  const lastRow2 = sheet2.getLastRow();

  sheet1.getRange("A" + lastRow1).copyTo(sheet2.getRange("D" + (lastRow2 + 1)));

}


Clark Lind

unread,
Nov 29, 2021, 9:55:44 AM11/29/21
to Google Apps Script Community
I'm guessing the target sheet needs more rows at the bottom.  You could add a check, something like the below untested code:
 
function myFunction() {
  const sheetName1 = "sheet1";
  const sheetName2 = "sheet2";
  const sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName1);
  const sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName2);
  const lastRow1 = sheet1.getLastRow();
  const lastRow2 = sheet2.getLastRow();
    if (lastRow2 >= sheet2.getMaxRows()) {
  sheet2.insertRowsAfter(lastRow2, 2);      //adds 2 rows to the bottom
Reply all
Reply to author
Forward
0 new messages