Alessandro
Alessandro

Reputation: 31

Copy a row's content to last row

i'm a neophyte at coding google apps script .

I was wondering if it's possible to write a code that automatically

  1. copies a first row's content (where i write email|name|phone number...)
  2. everytime, creates a new row at the bottom
  3. pastes the content from the first row to the last row created
  4. Makes first row's content (I already know how)

Then, I will link the code to a button. So, the first row should work like a simple form that easily brings new data to the end without scrolling the entire sheet. To start coding that, I registered a macro that does that

function insertlastrow1() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange(' **26:26** ').activate();  //activates last row
  spreadsheet.getRange('5:5').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false); //pastes from row 5
};

It simply activates last sheet's row and pastes content from row 5. The Range '26:26' should be replaced by 'last row' once it creates a new row. I think I should create a variable that would be wrote instead of absolute reference '26:26'.

I'm so sorry that it will appear a very stupid question but I started learning really a few time ago.

Upvotes: 3

Views: 1715

Answers (1)

Aerials
Aerials

Reputation: 4419

Using the getLastRow() method you can get the last row number.

Example:

function copyLastRow() {
  var sheet = SpreadsheetApp.getActive();
  var lastRow = sheet.getLastRow();
  var lastRowA1 = lastRow+":"+lastRow
  var newLastRow = (lastRow+1)+":"+(lastRow+1);
  sheet.getRange(lastRowA1).copyTo(sheet.getRange(newLastRow).activate(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
};

Upvotes: 2

Related Questions