简体   繁体   中英

Is there a way to remove a choice from google sheets dropdown menu if chosen more than a certain times?

I have a column which I have used data validation to add a dropdown list to. These are time slots. I want only two people to be able to choose a slot so I would like the option to disappear from the drop down list if it is repeated at least two times in the column. I was trying to do it with Choice Eliminator 2 from google forms but there is no info on the privacy policy so it is not easy to trust them. Is there a way to do that in google sheets?

You can do it with Google Apps Script. I have tried to replicate what you want to be done, so here it is.

Here are the sample outputs:

When options were picked just once:

样本输出1

When an option is picked more than once:

样本输出2

Column A is where the dropdown list bases its options.

Column B is where the answers are being checked.

Everytime the user edits the sheet, the script checks if an option is chosen more than once in column B. If it does find elements chosen more than once, they are then removed from the dropdown list.

Here is the code.

function onEdit(e){   
  var sheets = SpreadsheetApp.getActive();
  // 'max' is responsible how many the item can be chosen before being removed from the dropdown list
  const max = 1; 
  
  var dropdown = sheets.getRange('C2');
  var options = sheets.getRange('A2:A6');
  var answers = sheets.getRange('B2:B6');

  // create array to contain option and answer values and remove duplicates/invalid elements
  var optionsValues = options.getValues().flat().filter((item, i, ar) => ar.indexOf(item) === i).filter((item) => item.length !== 0);
  // we are not removing duplicates from the answer, as that will determine if how many the option has been chosen
  var answersValues = answers.getValues().flat().filter((item) => item.length !== 0);

  // remove more than once existence of options in column answers
  for (var i = 0; i < answersValues.length; i++) {
    if (answersValues.filter((item) => item == answersValues[i]).length > max) {
      // remove items that are more than 'max' allowed value
      optionsValues = optionsValues.filter((item) => item !== answersValues[i]);
    }
  }

  var rule = SpreadsheetApp.newDataValidation().requireValueInList(optionsValues).build();
  dropdown.setDataValidation(rule);
}

Code have comments and should be descriptive enough but if you have any questions and clarifications, don't hesitate to comment.

Also, make sure that you set up the triggers properly as it is needed for onEdit to properly work.

Does this achieve what you want to be done?

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