I'm using this code to search column 1 on a spreadsheet for the value 'Net Income'. I want this code to return the row position of with the value 'Net Income' so I can apply some formatting specific to that row based on that value. Here's the code I currently have:
const netIncomeRow = values.reduce((pos, row, i) => {
if(row[0] === 'Net Income') pos = i 1
return pos;
},0);
const netIncomeRange = sheet.getRange(netIncomeRow, 1, 1, sheet.getLastColumn());
netIncomeRange.setFontWeight('bold');
When I run the code, I get the error "Exception: The starting row of the range is too small." and cannot figure out how to fix this ):
*Edit - I was taught to search through the rows this way as the position of the 'Net Income' row will change over time and I would like the bold formatting to follow and apply to whatever row ends up with the value 'Net Income'.
CodePudding user response:
Prevent Error
const netIncomeRow = values.reduce((pos, row, i) => {
if(row[0] === 'Net Income') pos = i 1
return pos;
},0);
if(netIncomeRow) {
const netIncomeRange = sheet.getRange(netIncomeRow, 1, 1, sheet.getLastColumn());
netIncomeRange.setFontWeight('bold');
}
CodePudding user response:
If you want to get an index of a value in array you can use the method array.findIndex()
. Something like this:
const netIncomeRow = values.findIndex(x => x[0] == 'Net Income');
Here is the function:
function myFunction() {
var sh = SpreadsheetApp.getActiveSheet();
var values = sh.getDataRange().getValues();
var index = values.findIndex(x => x[0]== 'Net Income') 1;
if (index) sh.getRange(index,1,1,sh.getLastColumn()).setFontWeight('Bold');
}
Before:
After: