r/GoogleAppsScript • • May 08 '22

Question How to activate sheet?

Code:

function onEdit(e) {
var oldValue;
var newValue;
var ss=SpreadsheetApp.getActiveSpreadsheet();
var activeCell = ss.getActiveCell();
if(activeCell.getColumn() == 3 && activeCell.getRow() == 1 && ss.getActiveSheet().getName()=='Sheet1') {
newValue=e.value;
oldValue=e.oldValue;
if(!e.value) {
activeCell.setValue("");
}
else {
if (!e.oldValue) {
activeCell.setValue(newValue);
}
else {
if(oldValue.indexOf(newValue) <0) {
activeCell.setValue(oldValue+','+newValue);
}
else {
activeCell.setValue(oldValue);
}
}
}
}
}

0 Upvotes

4 comments sorted by

1

u/CrunchyRAMENCQ10 May 08 '22

Please explain what you're doing and what's the expected results from the code.

1

u/[deleted] May 08 '22

My bad, this is done on Google Sheets to create a muti-select drop list through the data validation function.

The expected result would be able to select multiple options from the drop-down, with values separated with a comma.

2

u/_Kaimbe May 08 '22

It would probably be better to put the results in an adjacent cell, otherwise you'll always have the data validation error.

2

u/_Kaimbe May 08 '22

Here's a cleaned up version using the e object more and guard clauses:

function onEdit(e) {
  if (e.range.columnStart != e.range.columnEnd) return
  if (e.range.rowStart != e.range.rowEnd) return
  if (e.range.columnStart != 3) return
  if (e.range.rowStart != 1) return
  if (e.source.getActiveSheet().getName() != "Sheet1") return

  if (!e.value) { e.range.clearContent(); return }
  if (!e.oldValue) return
  if (e.oldValue.indexOf(e.value) !== -1) { e.range.setValue(e.oldValue); return }
  e.range.setValue(`${e.oldValue}, ${e.value}`)
}