Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasbachem/de09475b2f2b4eb1167e06b74a53917d to your computer and use it in GitHub Desktop.
Save thomasbachem/de09475b2f2b4eb1167e06b74a53917d to your computer and use it in GitHub Desktop.
Google Sheets: Script to fix ROUNDUP() to be compatible with Excel export
// Excel needs ROUNDUP() to always have a second argument while in Google Sheets it defaults to 0.
// This script adds the missing ";0" to any use of ROUNDUP() in the current spreadsheet.
function fixRoundupForExcel() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Go thru each sheet
var sheets = ss.getSheets();
for (var s = 0; s < sheets.length; s++) {
var sheet = sheets[s];
var range = sheet.getDataRange();
// Go thru each cell formula
var formulas = range.getFormulas();
for (var r = 0; r < formulas.length; r++) {
for (var c = 0; c < formulas[r].length; c++) {
var formula = formulas[r][c];
if(formula) {
var fixed = false;
// Iterate over all occurrences of "ROUNDUP("
var offset = -1;
while ((offset = formula.toLowerCase().indexOf('roundup(', offset + 1)) != -1) {
// Parse possibly nested formula
var openBrackets = 0, inString = false;
formulaParsing:
for (var pos = offset, l = formula.length; pos < l; pos++) {
var char = formula.substr(pos, 1);
switch (char) {
case "'":
case '"':
// Keep track of whether we're in a string
inString = !inString;
break;
case '(':
// Keep track of open brackets
if (!inString) {
openBrackets++;
}
break;
case ')':
if (!inString) {
openBrackets--;
}
if(openBrackets == 0) {
// Separate complete ROUNDUP(...) function
var func = formula.substr(offset, pos - offset + 1);
// If there is no decimals argument
if (!func.match(/;\s*[0-9]+\s*\)$/)) {
// Insert ";0" decimals argument
formula = formula.substr(0, offset) + formula.substr(offset, pos - offset) + ';0' + formula.substr(pos);
fixed = true;
}
break formulaParsing;
}
}
}
}
if(fixed) {
sheet.getRange(r + 1, c + 1).setFormula(formula);
Logger.log(sheet.getName() + ': R' + (r + 1) + 'C' + (c + 1) + ': ' + formula);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment