Luciano GT
Luciano GT

Reputation: 23

GAS Google Script - How copy value and paste in another Cell

I need any need with Google script. I need copy value in the activate cell and paste in another cell.

In this moment my code is:

function onEdit(e) {
  

      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
      var cell = sheet.getActiveCell();
      var valueCell = cell.getValue();
      console.log(valueCell);

  }

I need to monitor the event, get the value and copy it to another column. (column B -> D; and column C -> E). This copy will be made cell by cell and not by cell range. Example: entered value in cell B5, copy to D5. Value entered in C5 I immediately copy to E5, successively.

example

Upvotes: 2

Views: 2607

Answers (2)

Marios
Marios

Reputation: 27350

Explanation:

Your goal is to copy the values from B->D and C->E when B or C are edited.

  • You need to take full advantage of the event object.

  • The following script will check whether the name sheet that was edited is dados. Then it will ensure that the edit was made after row 1 assuming you have headers. Finally, we only accept edits for columns B and C or column indexes 2 or 3:

    if(sh.getName() == 'dados' && row > 1 && [2,3].includes(col))

  • Then we use a ternary operator to make the code more efficient: sh.getRange(row,col+2).setValue(e.value);

Solution:

function onEdit(e) {
  const ss = e.source;
  const sh = ss.getActiveSheet();
  const row = e.range.getRow();
  const col = e.range.getColumn();
  
  if(sh.getName() == 'dados' && row > 1 && [2,3].includes(col)){
   sh.getRange(row,col+2).setValue(e.value);
  }
 }

Note:

To use this script, copy & paste the above code in a blank script in Tools => Script editor. Save the changes and then you automatically have the desired functionality in the sheet. You should not execute the function manually since it is a triggered function.

Upvotes: 1

Gav
Gav

Reputation: 393

You can try the below, this will work for you as long as it is a specific cell you wish to copy to:

function onEdit(e) {
  var val = e.value;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getActiveSheet();
  var copyTo = sh.getRange('A1').setValue(val); //<<<change the A1 to the cell you wish to copy to
}
}

Upvotes: 1

Related Questions