I'm attempting to build a function in google script that would allow me to code in certain column names (as these will remain constant), and to have said function find that column by the name, and create/insert a custom formula via conditional formatting to highlight duplicates in that column. The formula to find duplicates is =COUNTIF(E:E,E1)>1 (using column E as an example).
So to re-state, what I'm trying to do is:
- Have a function that inserts a new conditional format rule to highlight duplicates in a row
- Have the formula for the new conditional format be dynamic in case the column moves between data sets (although the column name will be the same)
- Have this function insert the conditional format into a column by name, instead of the number
I've tried to find something similar to this on stackoverflow but not finding much luck, just a few posts that are:
Custom Formula in Condition Format Rule Builder Script
Get column values by column name not column index
So this sheet would find the column "WOW":
Desired outcome/Would look like this after the function has ran (Highlight E2 and E2 in the WOW column):
So my attempt at making this code is below, however I'm hoping someone has a better idea as it's not quite working and this seems to be advanced coding (and I'm a newbie)
function conditionalformat1(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet1');//need to call the tab name as I have many tabs
var colName = 'WOW' //specific column name to have this function search for
var sheetName = 'sheet1'
var newRule = SpreadsheetApp.newConditionalFormatRule()
.whenFormulaSatisfied('=COUNTIF(E:E,E1)>1')//this should be dynamic instead what it is now...not sure if we can use R1C1 notation?
.setBackground('red')
.setRanges(getColByName)
.build()//similar setup to (https://stackoverflow.com/questions/50911538/custom-formula-in-condition-format-rule-builder-script) @Patrick Hanover & https://developers.google.com/apps-script/reference/spreadsheet/conditional-format-rule-builder#whenFormulaSatisfied(String)
var rules = sheet.getConditionalFormatRules();
rules.push(conditionalformat1);
sheet.setConditionalForatRules(rules);
function getColByName(colName) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet1');
var colName = 'WOW'
var data = sheet.getRange("1:1000").getValues();//have it search the entire sheet?
var col = data[0].indexOf(colName);
if (col != -1) {
return data[row-1][col];
}
}// via the question & author https://stackoverflow.com/questions/36346918/get-column-values-by-column-name-not-column-index @Leonardo Pina
}//end of conditionalformat1 conditional formatting
Thanks for the help in advance, this will be great to learn how to have functions find columns by name and execute items.