IAmMoonie

Untitled

Jan 6th, 2023
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function onEdit({ range }) {
  2.   // Define user-defined variables so they can easily be edited
  3.   let rows = [2, 3, 4]; // array of rows to process
  4.   let columns = [2, 3, 4]; // array of columns to process
  5.   let targetCell = "G4"; // target cell to
  6.  
  7.   // Get the edited cell and its value
  8.   let editedCell = range;
  9.   let editedColumn = editedCell.getColumn();
  10.   let editedRow = editedCell.getRow();
  11.   let editedValue = editedCell.getValue();
  12.  
  13.   // Check if edited cell is within the specified rows and columns
  14.   if (!rows.includes(editedRow) || !columns.includes(editedColumn)) {
  15.     return; // exit if not in the correct range
  16.   }
  17.  
  18.   try {
  19.     // Validate that the edited cell contains a numeric value
  20.     if (isNaN(parseFloat(editedValue))) {
  21.       throw new Error(`The edited cell must contain a numeric value.`);
  22.     }
  23.  
  24.     // Get the values of the row that was edited
  25.     let rowValues = editedCell
  26.       .getSheet()
  27.       .getRange(editedRow, columns[0], 1, columns.length)
  28.       .getValues()[0];
  29.  
  30.     // Calculate the price minus the value of the edited cell
  31.     let x = editedCell.getSheet().getRange(targetCell).getValue() - editedValue;
  32.  
  33.     // Calculate the number of cells in the row that were not edited
  34.     let numUneditedCells = rowValues.length - 1;
  35.  
  36.     // Calculate the value to be written to the unedited cells
  37.     let valueToWrite = x / numUneditedCells;
  38.  
  39.     // Write the value to the unedited cells
  40.     for (let i = 0; i < rowValues.length; i++) {
  41.       if (rowValues[i] !== editedValue) {
  42.         editedCell
  43.           .getSheet()
  44.           .getRange(editedRow, columns[i])
  45.           .setValue(valueToWrite);
  46.       }
  47.     }
  48.   } catch (error) {
  49.     console.error(error);
  50.   }
  51. }
Tags: JavaScript
Advertisement
Add Comment
Please, Sign In to add comment