简体   繁体   中英

Google App Scripts: How to find first empty cell in row, check value in next column and set values accordingly

I am trying to write a Google App script that looks through the values in column A on my spreadsheet. If it finds an empty value, it should check the cell directly to the right, in column B. If the value in the cell directly to the right == "Planned" then it should ignore and continue to the next empty cell in Column A.

This should loop through all empty cells in Column A.

If the value in Column B to the right of the empty cell in Column A == "Open" then it should set the value of the empty cell in Column A to "X".

It should loop through every empty cell in Column A and every corresponding cell in Column B until it has confirmed that there are no cases where Column A contains an empty value and Column B contains an "Open" value.

Thank you in advance for any and all help!

Sample data:

样本数据

Output after running script:

样本输出

This code is pretty self descriptive. Kindly check the code comments. If you have any questions, feel free to comment below

function updateSheet() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var rows = sheet.getLastRow() - 1;
  var colARange = sheet.getRange(2, 1, rows, 1);
  var colBRange = sheet.getRange(2, 2, rows, 1);

  // 2d array -> 1d array for easier data accessibility
  var colAValues = colARange.getValues().flat();
  var colBValues = colBRange.getValues().flat();

  for(var i = 0; i < rows; i++) {
    // If A is blank and B is 'Open', set A to 'X'
    if(!colAValues[i] && colBValues[i] == 'Open') {
      sheet.getRange(i + 2, 1).setValue('X');
    }
  }
}
function checkEmptyCells() {
    const range = SpreadsheetApp.getActiveSheet().getRange('A:B')
    // Get the value of column A & B
    const values = range.getValues()
    const length = values.length
    let r = -1
    // Loop through checking for empty "" cells in column A
    while (++r < length) {
        if (values[r][0] == '') {
          // assign value "X" if A is an empty cell and B is "Open"
          values[r][0] = values[r][1] === 'Open' ? 'X' : ''
        }
    }
    range.setValues(values)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM