Rearranging Columns on Google Spreadsheet using Google Apps Script
This is a sample script for rearranging the columns on Google Spreadsheet using Google Apps Script.
Sample script
In this sample script, the columns are rearranged with an array including the rearranged column indexes.
function rearrangeColumns(sheet, ar) {
var obj = ar.reduce(function(ar, e, i) {
return ar.concat({ from: e + 1, to: i + 1 });
}, []);
obj.sort(function(a, b) {
return a.to < b.to ? -1 : 1;
});
obj.forEach(function(o) {
if (o.from != o.to) sheet.moveColumns(sheet.getRange(1, o.from), o.to);
obj.forEach(function(e, i) {
if (e.from < o.from) obj[i].from += 1;
});
});
}
// Please run this function.
function main() {
var sheet = SpreadsheetApp.getActiveSheet();
var rearrangedColumnIndexes = [4, 3, 1, 0, 2];
rearrangeColumns(sheet, rearrangedColumnIndexes);
}
-
rearrangedColumnIndexesis the indexes of rearranged columns.