Created
December 4, 2023 21:24
-
-
Save dtturcotte/d56f39599ccdd39c3f59597f417fdce5 to your computer and use it in GitHub Desktop.
addOrUpdateRecord Google Sheets App Script: randomly add / update a record (based on Trigger, or manual function execution)
This file contains 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
/* | |
Randomly add or update (change value column for a row) a record | |
*/ | |
function randomlyAddOrUpdateRecord() { | |
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('president_primary_polls_test') | |
// Force the spreadsheet changes to be applied | |
SpreadsheetApp.flush() | |
const lastRow = sheet.getLastRow() | |
// 50% chance | |
// const addNewRecord = Math.random() < 0.5 | |
const addNewRecord = false | |
// const addNewRecord = true | |
let rowData | |
// Add a new record (if addNewRecord is true, or there aren't records) | |
if (addNewRecord || lastRow === 1) { | |
// Assuming IDs are sequential for simplicity | |
const newId = lastRow | |
const newName = "Name_" + newId | |
const newValue = Math.floor(Math.random() * 100) | |
rowData = [newId, newName, newValue] | |
sheet.appendRow(rowData) | |
rowData = [rowData] | |
} | |
// Update existing record | |
else { | |
// Select a random row to update (exclude header row); +2 to avoid header row | |
const randomRow = Math.floor(Math.random() * (lastRow - 1)) + 2 | |
const newValue = Math.floor(Math.random() * 100) | |
// Column 3 (C) for 'value' column | |
sheet.getRange(randomRow, 3).setValue(newValue) | |
rowData = sheet.getRange(randomRow, 1, 1, 3).getValues() | |
} | |
// Call onEditWebhook.gs's atEdit function and pass in modified / added data | |
try { | |
atEdit(rowData, true) | |
} | |
catch (error) { | |
console.error("Error in randomlyAddOrUpdateRecord:", e.toString()) | |
} | |
} | |
/* | |
Trigger-activated function to add / update record | |
*/ | |
function randomIntervalTrigger() { | |
const executionProbability = 1 | |
if (Math.random() < executionProbability) { | |
randomlyAddOrUpdateRecord() | |
} | |
} | |
/* | |
Provide custom menu ui in spreadsheet for user to manually add / update record | |
*/ | |
function onOpen() { | |
const ui = SpreadsheetApp.getUi() | |
ui.createMenu('Custom Scripts') | |
.addItem('Random Add or Update', 'randomlyAddOrUpdateRecord') | |
.addToUi() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment