问题
I am trying to figure out how to use conditional formatting via script on a google spreadsheet similar to what you can do with the conditional formatting feature.
I have two columns labeled 'Country' and 'State.' If the value in one cell is 'United States,' I want the script to check the adjacent state column to make sure it's not blank. If it is, I want the cell background to change to red.
Is there any way to do this in a script? I don't want to use the built in feature as it doesn't copy over to newly create sheets within the spreadsheet as I'll be having other users creating new sheets.
I found some references, but I'm having trouble tailoring them to my needs.
Links: Google Spreadsheet conditional formatting script
https://webapps.stackexchange.com/questions/16745/google-spreadsheets-conditional-formatting-based-on-another-cells-content
回答1:
Let's assume that Country is placed at (1,1) and State is placed at (1,2) where (i,j) indicates the ith row and jth column on the Spreadsheet. Google Spreadsheets is 1-indexed meaning indices start at 1.
var activeSheet = SpreadsheetApp.getActiveSheet();
for (var a = 2; a < activeSheet.getLastRow(); a++) {
if (String(activeSheet.getRange(a,1).getCell(1,1)) === "United States") {
if (String(activeSheet.getRange(a,2).getCell(1,1)) === null) {
activeSheet.getRange(a, 2, 1, 1).setBackgroundColor('red');
}
}
}
回答2:
Try copy and pasting this into a blank script file. This depends on column A being Country, and column B being State, but you can make as many sheets as you want, and this will work automatically.
Let me know if you want an explanation of a specific part, as I'm not sure what your scripting background is. I've included some comments in the code.
function onEdit(e) {
var ss = e.source;
var sheet = ss.getActiveSheet();
var range = sheet.getRange("A:B");
var values = range.getValues();
//for each row that data is present
for(var i = 0; i < values.length; i++) {
var cell = sheet.getRange(i + 1, 2);
//check if the first value of that row is exactly "United States"
if(values[i][0] === "United States") {
//if it is, check for a blank cell. If so, make it red.
if(values[i][1] === "") {
cell.setBackground('red');
} else {
cell.setBackground('white');
}
} else {
//In any other case, make it white.
cell.setBackground('white');
}
}
}
来源:https://stackoverflow.com/questions/28822055/google-app-script-conditional-formatting-based-on-another-cell