Last active
November 20, 2018 10:16
-
-
Save eob/0ba8405e315ed4afeaaafad788db64f5 to your computer and use it in GitHub Desktop.
Auto-Incrementing Columns on Google Spreadsheets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function myFunction() { | |
var AUTOINC_COLUMN = 0; | |
var HEADER_ROW_COUNT = 1; | |
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); | |
var worksheet = spreadsheet.getSheetByName("Sheet1"); | |
var rows = worksheet.getDataRange().getNumRows(); | |
var vals = worksheet.getSheetValues(1, 1, rows+1, 2); | |
for (var row = HEADER_ROW_COUNT; row < vals.length; row++) { | |
try { | |
var id = vals[row][AUTOINC_COLUMN]; | |
Logger.log(id);Logger.log((""+id).length ===0); | |
if ((""+id).length === 0) { | |
// Here the columns & rows are 1-indexed | |
worksheet.getRange(row+1, AUTOINC_COLUMN+1).setValue(row); | |
} | |
} catch(ex) { | |
// Keep calm and carry on | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had to change line 8 to
var rows = worksheet.getDataRange().getNumRows() - 1;
in order to apply it properly to my spreadsheet. I had one header row, but the script was adding an ID to one row below my actual data.