简体   繁体   中英

How to capitalize all sheet except specific columns on Google spreadsheet using Google Script?

This code capitalize all the sheet cells, except some columns as required. Nevertheless, formulas into the excluded cells are deleted. I do not want the script erase my formulas into these columns.

 function onOpen() { var ui = SpreadsheetApp.getUi(); ui.createMenu('Eta Buddy') .addItem('Capitalize', 'proper') .addToUi(); } function proper() { var s = SpreadsheetApp.getActiveSheet(), excludedCols = [2, 4, 6, 8, 10]; s.getDataRange() .setValues( s.getDataRange() .getValues() .map(function (r) { return r.map(function (el, i) { return !el ? null : (typeof el !== 'string' && el) || excludedCols.indexOf(i + 1) > -1 ? el : toTitleCase(el); }) }) ) } function toTitleCase(str) { return str.replace(/\\w\\S*/g, function (txt) { return txt.charAt(0) .toUpperCase() + txt.substr(1) .toLowerCase(); }); } 

Please take note of Zig's comment. Since very little needs to be changed, replace your proper function with the one below and see if that works..

UPDATED CODE (to save the formulas in the excluded columns, see comment)

function proper() {
var s = SpreadsheetApp.getActiveSheet(),
    excludedCols = [2, 4, 6, 8, 10];
formulas = s.getDataRange()
    .getFormulas()
s.getDataRange()
    .setValues(
        s.getDataRange()
        .getValues()
        .map(function (r, j) {
            return r.map(function (el, i) {
                return !el ? null : formulas[j][i] ? formulas[j][i] :
                    (typeof el !== 'string' && el) || excludedCols.indexOf(i + 1) > -1 ? el : toTitleCase(el);
            })
        })
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM