setNumberFormatsByHeader(sheet, formats) finds each column by its header in row 1 and applies a number format to that column's data rows. Pass an object such as {"Price": "$#,##0.00", "Due": "yyyy-mm-dd"}. A header it cannot find is skipped with a log line instead of throwing, so one renamed column does not stop the rest.
When to use
- A sheet where columns move around but the header names stay put
- Setting currency and date formats after a script writes raw values
- Formatting a freshly imported tab without hard-coding column letters
How to use this snippet
Header matching ignores case and surrounding spaces. If a header appears twice, the first column wins. The formats go on rows 2 to the last row; the header row is left alone. It returns {applied, skipped} so you can check what happened.
/**
* Apply number formats to data rows (row 2 down) by header name in row 1.
* formats is {headerName: formatString}. Headers that are not found are
* skipped with a console.log line, not thrown. Returns {applied: string[],
* skipped: string[]}.
*
* @param {GoogleAppsScript.Spreadsheet.Sheet} sheet
* @param {Object<string, string>} formats
* @return {{applied: string[], skipped: string[]}}
*/
function setNumberFormatsByHeader(sheet, formats) {
var applied = [];
var skipped = [];
var names = Object.keys(formats || {});
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
if (!names.length) return { applied: applied, skipped: skipped };
if (lastRow < 1 || lastCol < 1) {
console.log('setNumberFormatsByHeader: sheet has no header row');
return { applied: applied, skipped: names };
}
var headers = sheet.getRange(1, 1, 1, lastCol).getValues()[0];
for (var n = 0; n < names.length; n++) {
var want = String(names[n]).trim().toLowerCase();
var col = -1;
for (var c = 0; c < headers.length; c++) {
if (String(headers[c]).trim().toLowerCase() === want) {
col = c + 1;
break;
}
}
if (col < 0) {
console.log('setNumberFormatsByHeader: header not found, skipped: ' + names[n]);
skipped.push(names[n]);
continue;
}
if (lastRow >= 2) {
sheet.getRange(2, col, lastRow - 1, 1).setNumberFormat(formats[names[n]]);
}
applied.push(names[n]);
}
return { applied: applied, skipped: skipped };
}
Example
function formatInvoices() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Invoices');
var result = setNumberFormatsByHeader(sheet, {
'Price': '$#,##0.00',
'Due': 'yyyy-mm-dd',
'Qty': '0'
});
if (result.skipped.length) {
console.log('Not formatted: ' + result.skipped.join(', '));
}
}
Notes
setNumberFormatchanges how a value is shown. A date that is stored as text stays text, so fix the values first if the format has no effect.- Formats use the same patterns as Format → Number → Custom number format in the Sheets menu.
- The format is applied to the cells that exist now. Rows added later need another run.
Happy Coding!
