Reputation: 968
I want to make a macro in Google sheet for the following case
In a worksheet column, say column J, The allowed text inputs are "A", "B" and "C".
As soon as I put A
, B
or C
(in the J
th column) the cell background color should change to "Green", "Yellow" & "Red" respectively.
How can I do that?
I don't know much about macros, I just got the task to do so. Can I get some help?
Upvotes: 1
Views: 3875
Reputation: 201503
If my understanding is correct, how about these 2 sample scripts? Please think of this as just one of several answers.
In this sample script, "OnEdit" event of the simple triggers is used.
Please copy and paste the following script to the script editor, and save it. Then, please put the value to the column "J".
function onEdit(e) {
if (e.range.getColumn() == 10) {
var colors = {A: "green", B: "yellow", C: "red"};
if (Object.keys(colors).indexOf(e.value) > -1) {
e.range.setBackground(colors[e.value]);
} else {
e.range.setValue("");
}
}
}
In this sample script, set both Data Validation and Conditional Format Rule to the column "J".
Please copy and paste the following script to the script editor, and save it. Then, run myFunction()
on the script editor. In this script, the condition works by running the script only once.
function myFunction() {
var rangeA1Notation = "J:J"; // Column "J"
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(rangeA1Notation);
// Set Data Validation
var rule = SpreadsheetApp.newDataValidation().withCriteria(SpreadsheetApp.DataValidationCriteria.VALUE_IN_LIST, [["A", "B", "C"], false]).setAllowInvalid(false).build();
range.setDataValidation(rule);
// Set Conditional Format Rule
var rules = sheet.getConditionalFormatRules();
rules.push(SpreadsheetApp.newConditionalFormatRule().whenTextEqualTo("A").setBackground("green").setRanges([range]).build());
rules.push(SpreadsheetApp.newConditionalFormatRule().whenTextEqualTo("B").setBackground("yellow").setRanges([range]).build());
rules.push(SpreadsheetApp.newConditionalFormatRule().whenTextEqualTo("C").setBackground("red").setRanges([range]).build());
sheet.setConditionalFormatRules(rules);
}
If these methods were not what you want, I apologize.
Upvotes: 2