Search code examples
google-apps-scriptgoogle-sheetseventsevent-handling

How could I create a function with Google Apps Script to add strikethrough to a row of cells if another cell's value met a condition?


The goal is to create a script that automatically adds strikethrough to text across a row when the last cell in a row's value is changed to "FOUND!"

This is what I have so far:

function strikethroughRow(row) {
  const ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Records");
 
  const firstCell = "B" + row;
  const secondCell = "A" + row;
  
  firstCell.setFontLine("line-through"); 
  secondCell.setFontLine("line-through");
}

function onEdit(e) {
  const column = e.getColumn();
  const value = e.getValue();

  if(column === 3.0 && value === "FOUND!"){
    const row = e.getRow();
    strikethroughRow(row);
  }
}

Solution

  • From your question and your showing script, I believe your goal is as follows.

    • When a value of "FOUND!" is put into column "C", you want to set the strikethrough to columns "A" and "B".

    Modification points:

    • In your script, e.getColumn(), e.getValue() and e.getRow() are not correct. In this case, it is required to use e.range.
    • firstCell and secondCell are string value. By this, an error occurs.

    I thought that in this case, the script might be able to be simpler. So, how about the following modification?

    Modified script:

    function onEdit(e) {
      const sheetName = "Sheet1"; // Please set your sheet name.
      const { range } = e;
      const sheet = range.getSheet();
      const value = range.getValue();
      if (sheet.getSheetName() != sheetName || range.columnStart != 3 || value != "FOUND!") return;
      sheet.getRange(range.rowStart, 1, 1, sheet.getLastColumn() - 1).setFontLine("line-through");
    }
    

    Note:

    • If the last column is not column "C", how about the following modified script?

      function onEdit(e) {
        const sheetName = "Sheet1"; // Please set your sheet name.
        const { range } = e;
        const sheet = range.getSheet();
        const value = range.getValue();
        const lastColumn = sheet.getLastColumn();
        if (sheet.getSheetName() != sheetName || range.columnStart != lastColumn || value != "FOUND!") return;
        sheet.getRange(range.rowStart, 1, 1, sheet.getLastColumn() - 1).setFontLine("line-through");
      }
      

    Reference: