Search code examples
google-apps-scriptgoogle-sheetscopy-paste

Copy values from edited cell to a new one


i've been trying to figure out how to copy values from one cell to another with App Script. I'm not very much of a programmer myself but still i'm willing to learn.

Here is an example of what i need to achieve:

Sheet 1 contains a menu of products with the selling price

Product Price
Salad $6

And so on...

Sheet 2

I've made a selling point in this sheet where you register sales and purchases. if its a sale... when you pick a product it will get you the price tag on the menu and the multiply it for the quantity of sales example:

S or P Product Price Quantity Total
Sale Salad $6 2 $12

The thing is that i need to change the price tag on the menu but i don't want to modify past data entries (Col 'Total') with this change so i figured it would be best if somehow i could manage to copy the first value that appears on 'Total' to a new column

Any ideas?

so far i have been trying to modify this script and trying to make it work for a copy paste but i don't have idea on what i'm doing :)


function onEdit(e){
  //variables
  var startRow = 2;
  var targetColumn = 5;
  var ws = "Sheet 1";
  
  //get modified row and column
  var row = e.range.getRow();
  var col = e.range.getColumn();
  
  if(col === targetColumn && row >= startRow && e.source.getActiveSheet().getName() === ws){
    
//Lost at this point...

  }
}

Hope someone out there could help me :)


Solution

  • If I understand correctly, what you want is whenever you edit the price of the item, the value in 'Total' will be copied and pasted to another column and the 'Total' will now have the price*quantity as its new value. Am I correct?

    If so, you can try the code below which I based on your code in the post. It will trigger whenever you edit the value of 'Price' and will move the previous value of 'Total' to another column 'Previous Total' and will automatically update the 'Total' based on the Price input and the value in 'Quantity'.

    function onEdit(e){
      //variables
      var startRow = 2;
      var targetColumn = 3;
      var ws = "Sheet1";
      
      //get modified row and column
      var row = e.range.getRow();
      var col = e.range.getColumn();
      
      if(col === targetColumn && row >= startRow && e.source.getActiveSheet().getName() === ws){
    //Lost at this point...
        price = e.range.getValue();
        quantity = e.range.offset(0,1).getValue();
        prevTotal = e.range.offset(0,2).getValue();
        e.range.offset(0,2).setValue(price*quantity);
        e.range.offset(0,3).setValue(prevTotal);
      }
    }
    

    Previous Sample Value:

    enter image description here

    After Edit Sample Value:

    enter image description here