I`m trying to write a script that can find the maximum value in a specific column (proportion column in the given dataset) and highlight the cell accordingly.
Below is where I am at so far
JavaScript
x
22
22
1
function myFunction() {
2
var ss = SpreadsheetApp.getActive();
3
var sh = ss.getSheetByName('Sheet1');
4
var range = sh.getRange("G2:G17");
5
var values = range.getValues();
6
var newRange = SpreadsheetApp.getActiveSheet().getRange(2, 7, values.length, 1).getValues();
7
var maximumproportion = Math.max.apply(Math, newRange);
8
var maxarr = [];
9
maxarr.push(maximumproportion)
10
var backgrounds = [];
11
var fontColors = [];
12
13
range.sort([{column:7, ascending: false}]); // sort by number is column 7
14
15
if (newRange === maxarr) {
16
backgrounds.push(["green"])
17
}else{
18
backgrounds.push([null])
19
}
20
SpreadsheetApp.getActiveSheet().getRange(2,7,values.length,1).setBackgrounds(backgrounds);
21
}
22
And below is the dataset I am using for this
so if the above code properly worked, it should`ve highlighted the first row in the last column which is 0.27% as this is the maximum value found in this column.
For the below part, I`ve also tried using for loop. But no luck there
Can someone please advise on how i can get this work?
JavaScript
1
12
12
1
// find the max value in Column G
2
for (var i = 1; i < 17; i++) {
3
console.log(newRange[i][0])
4
if (newRange[i] === maxarr[i]) {
5
backgrounds.push(["green"]);
6
} else {
7
backgrounds.push([null]);
8
}
9
}
10
SpreadsheetApp.getActiveSheet().getRange(2,7,16,1).setBackgrounds(backgrounds);
11
}
12
Advertisement
Answer
Answer 1
You can highlight the maximum value in a specific column using Conditional formatting.
Steps
- Go to
Format > Conditional formatting
- Select the range to apply the format
- Select
Custom formula is
inFormat cells if
- Apply
=(G:G)=MAX(G:G)
to select the cell with highest value
Answer 2
You can get and highlight the highest value in a simple way:
JavaScript
1
12
12
1
function myFunction() {
2
var ss = SpreadsheetApp.getActive();
3
var sh = ss.getSheetByName('Sheet1');
4
var range = sh.getRange("D2:D14")
5
var values = range.getValues();
6
var merged = [].concat.apply([], values);
7
var max = Math.max.apply(Math,merged)
8
var maxid = merged.indexOf(max)
9
range.getCell(maxid+1,1).setBackgroundRGB(0,255,0)
10
}
11
12
Explanation
var merged = [].concat.apply([], values)
transforms an array of arrays into an array of integers.var max = Math.max.apply(Math,merged)
gets the highest value of the rangevar maxid = merged.indexOf(max)
gets the index of the highest valuerange.getCell(maxid+1,1).setBackgroundRGB(0,255,0)
change the background of the desired cell. Keep in mind that the index of the array starts from 0 and the index from the cell from 1, so you have to sum 1 to the index. Furthermore, in RGB, green is equal tozero red, full green, zero blue
.