javascript - How to only return odd columns - Stack Overflow

admin2025-04-26  3

How would I edit this script to only return odd columns in the range?

function onEdit() {
  var s = SpreadsheetApp.getActiveSheet(); if (s.getName() == "2025 Attendance") {
    var r = s.getActiveCell(); if (r.getColumn() >= 3 && r.getColumn() <= 20) {
      var nextCell = r.offset(0, 1); if (nextCell.getValue() === '') //checks whether the adjacent cell is empty or not 
        nextCell.setValue(new Date());
    }
  }
}

I've tried changing the range but I can't figure out how to set the range to only odd numbers.

How would I edit this script to only return odd columns in the range?

function onEdit() {
  var s = SpreadsheetApp.getActiveSheet(); if (s.getName() == "2025 Attendance") {
    var r = s.getActiveCell(); if (r.getColumn() >= 3 && r.getColumn() <= 20) {
      var nextCell = r.offset(0, 1); if (nextCell.getValue() === '') //checks whether the adjacent cell is empty or not 
        nextCell.setValue(new Date());
    }
  }
}

I've tried changing the range but I can't figure out how to set the range to only odd numbers.

Share Improve this question edited Jan 15 at 14:14 Wicket 38.8k9 gold badges80 silver badges195 bronze badges asked Jan 15 at 5:26 Sean KilgoSean Kilgo 211 silver badge2 bronze badges 1
  • This question is similar to: How to determine if a number is odd in JavaScript. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – miken32 Commented Jan 16 at 15:50
Add a comment  | 

2 Answers 2

Reset to default 1

Affect only odd-numbered column

You can try this modified version of your code:

Code

function onEdit() {
  var s = SpreadsheetApp.getActiveSheet();
  if (s.getName() == "2025 Attendance") {
    var r = s.getActiveCell();
    if (r.getColumn() >= 3 && r.getColumn() <= 20 && r.getColumn() % 2 !== 0) {
      var nextCell = r.offset(0, 1);
      if (nextCell.getValue() === '') { // Checks whether the adjacent cell is empty or not 
        nextCell.setValue(new Date());
      }
    }
  }
}

I added r.getColumn() % 2 !== 0 which effectively checks if the column being edited is an odd-numbered column and adds it to your other conditions.

Sample Output

Edited Cell Cell to populate with date
Test edit 1/15/2025

References:

  • Determine if a number is odd in JavaScript
  • JavaScript Modulo
function onEdit(e) {
  const sh = e.range.getSheet();
  if(sh.getName() == '2025 Attendance' && ~[3,5,7,9,11,13,15,17,19].indexOf(e.range.columnStart)) {
    if(e.range.offset(0,1).getValue() == "") {
      e.range.offset(0,1).setValue(new Date())
    }
  }
}
转载请注明原文地址:http://www.anycun.com/QandA/1745598397a90985.html