function onEdit(e) {
var sheet = e.source.getActiveSheet();
var cell = e.range;
//Check if modified cell is Sheet1!B3
if(sheet.getName() == 'Sheet1' && cell.getA1Notation() == 'B3'){
//Change formula in Sheet1!B4
var unit = cell.getValue();
var formula = '=sum(B8:B'+(8+unit-1)+')';
Logger.log(formula);
sheet.getRange('B4').setFormula(formula);
//Clear output in Sheet1 starting from row 8 for Column A and B (including format)
sheet.getRange(8,1,sheet.getLastRow(),2).clear();
//Create an output data
var output = [];
for(var i=0; i<unit; i++){
output.push([i+1,""]);
}
output.push(["Total",formula]);
Logger.log(output);
sheet.getRange(8,1,output.length,output[0].length).setValues(output);
var yellow = '#ffff00';
var orange = '#ff9900';
//Add background color 'orange' to column A
sheet.getRange(8,1,unit,1).setBackgroundColor(orange);
//Add background color 'yellow' to column B
sheet.getRange(8,2,unit,1).setBackgroundColor(yellow);
}
}
What it does?
- Get the active sheet and the modified cell using the Google Sheets event objects
e.source
and e.range
- Check if the modified cell is in Sheet1!B3
- Get the value of the modified cell
- Create a SUM formula based on the input value
- Set the formula in Sheet1!B4
- Clear the content of Sheet1 for Column A and B starting in row 8
- Create a 2-d array
[(Unit#),(Empty Cell Rent)]
. Append ["Total", (SUM formula)]
at the end of the array
- Write the 2-d array output in Sheet1, starting from Column A row 8
- Set background colors for column A and column B
Note:
Since we used Google Sheets event objects, you cannot run this function in your Apps Script editor. Event object is undefined. If you want to debug the code, include logs in the code then modify a cell in your sheet to trigger the onEdit() which contains the event object then check the execution tab for the latest logs
Output:
