[英]How do I add Google sheets data vaildation to a column using apps script for cells to only allow colors and hex color codes to be inputted
see image of spreadsheet here example: Google sheet cells may only allow "brown", "red", "green" etc. and hex color codes to be inputted eg #03fca9.请参阅此处的电子表格图像示例:Google 表格单元格可能只允许输入“棕色”、“红色”、“绿色”等和十六进制颜色代码,例如#03fca9。 How would one go about this using apps script for an entire column?如何使用整个专栏的应用程序脚本来解决这个问题? Any help would be greatly appreciated!任何帮助将不胜感激!
You can use Apps Script for validation but you don't have to.您可以使用 Apps 脚本进行验证,但不是必须的。 Highlight the target range, select 'Data validation' -> 'Custom formula is' and input the formula below:突出显示目标范围,选择“数据验证”->“自定义公式是”并输入以下公式:
=REGEXMATCH(A1,"([#0-9a-fA-F]){6}|green|red|blue|purple")
The validation will be based on whether the formula evaluates to TRUE.验证将基于公式的计算结果是否为 TRUE。 I'm not an expert in REGEX so there might be better options to write this expression.我不是 REGEX 的专家,所以可能有更好的选择来编写这个表达式。 For example, my expression will not reject whitespaces, etc. The downside is that you'll have to list all colour aliases manually.例如,我的表达式不会拒绝空格等。缺点是您必须手动列出所有颜色别名。 Also, the expression only tests user input against the pattern - there's no way to check if the input is a valid colour.此外,该表达式仅根据模式测试用户输入 - 无法检查输入是否为有效颜色。
In code, you can do the same by calling this method of the DataValidationBuilder class to build a rule and apply it to the range在代码中,您可以通过调用 DataValidationBuilder 类的此方法来构建规则并将其应用于范围
var range = SpreadsheetApp.getActive().getRange('A1:A');
var rule = SpreadsheetApp.newDataValidation().requireFormulaSatisfied('=REGEXMATCH(A1,"([#0-9a-fA-F]){6}|green|red|blue|purple")').build();
range.setDataValidation(rule);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.