I have the following script provided by @ZektorH in another question of mine.
function onEdit(e) {
if (e.range.getColumn() ==2) {
//User edited the date co
I've reworked your code a bit, basically adding a condition to check whether the value in each cell equals "ENDED", and only deleting data if that's the case:
// Delete all "ENDED" values:
var resetRange = sheets.getRange(e.range.getRow(), e.range.getColumn() + 1, 1, sheets.getMaxColumns() - e.range.getColumn());
var resetValues = resetRange.getValues()[0];
for(var i = 0; i < resetValues.length; i++) {
if(resetValues[i] == "ENDED") {
var resetCell = sheets.getRange(e.range.getRow(), e.range.getColumn() + 1 + i);
resetCell.clearContent();
}
}
And also this, which deletes corresponding "ENDED" values if you edit to a later date:
// Clear past dates if new date is later:
var beforeDate = sheets.getRange(rowNum, colOffset, 1, foundCol);
var beforeValues = beforeDate.getValues()[0];
for(var i = 0; i < beforeValues.length; i++) {
if(beforeValues[i] == "ENDED") {
sheets.getRange(rowNum, colOffset + i).clearContent();
}
}
So, full code would be like this:
function onEdit(e) {
if (e.range.getColumn() == 2) {
//User edited the date column
if (typeof e.range.getValue() === typeof new Date()) {
//Value of edit was a date
endColumns(e.range.getRow(), e.range.getValue());
} else if (e.range.getValue() === "" || e.range.getValue() === null) {
var sheets = SpreadsheetApp.getActiveSheet();
// Delete all "ENDED" values:
var resetRange = sheets.getRange(e.range.getRow(), e.range.getColumn() + 1, 1, sheets.getMaxColumns() - e.range.getColumn());
var resetValues = resetRange.getValues()[0];
for(var i = 0; i < resetValues.length; i++) {
if(resetValues[i] == "ENDED") {
var resetCell = sheets.getRange(e.range.getRow(), e.range.getColumn() + 1 + i);
resetCell.clearContent();
}
}
}
}
}
function endColumns(rowNum, limitDate) {
var sheets = SpreadsheetApp.getActiveSheet();
var colOffset = 3; //Offset to account for your row Headers
var dateHeader = sheets.getRange(1, colOffset, 1, sheets.getMaxColumns() - colOffset);
var availableDates = dateHeader.getValues()[0];
var foundCol = 0;
for (var i = 0; i < availableDates.length; i++) {
if (availableDates[i] >= limitDate) {
break;
}
foundCol++;
}
var rewriteCells = sheets.getRange(rowNum, foundCol + colOffset, 1, sheets.getMaxColumns() - (foundCol + colOffset - 1));
//Add your formatting and text below:
rewriteCells.setValue("ENDED");
// Clear past dates if new date is later:
var beforeDate = sheets.getRange(rowNum, colOffset, 1, foundCol);
var beforeValues = beforeDate.getValues()[0];
for(var i = 0; i < beforeValues.length; i++) {
if(beforeValues[i] == "ENDED") {
sheets.getRange(rowNum, colOffset + i).clearContent();
}
}
// Clear all cells that are "white" (no header)
for (var i = 0; i < availableDates.length; i++) {
if (availableDates[i] === "" || availableDates[i] === null) {
sheets.getRange(rowNum, colOffset+i).clear();
}
}
}
I hope this is of any help to you.