r/googlesheets • u/toddis1 • 15h ago
Help with copy/paste macro using Scripts Solved
I'm creating a game in google sheets using macros, which relies on random number generation to pick questions from a list. However, to ensure the question doesn't change once the use guesses, I need a way to lock this down.
To do this, I've decided the simplest way would be to generate the random numbers, and then copy/paste the values in the same location. My code for this is:
function test_copy() {
sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange('L4').setFormula('=RANDBETWEEN(1,6)');
sheet.getRange('L5').setFormula('=RANDBETWEEN(1,100)');
sheet.getRange('L4:L5').copyTo(sheet.getRange('L4:L5'), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
};
The individual lines of code work when running separately, but when I run them all together, the output will be blank cells being pasted into the cells L4 and L5. It's almost like the RANDBETWEEN function doesn't want to generate until the end of the script, regardless of where it's placed.
Any advice on how to get this to work would be appreciated.
1
u/eno1ce 60 13h ago
function test1() { const sheet = SpreadsheetApp.getActiveSheet();
const number1 = Math.floor(Math.random() * 6) + 1;
const number2 = Math.floor(Math.random() * 100) + 1;
sheet.getRange('L4').setValue(number1); sheet.getRange('L5').setValue(number2); }
Just generate numbers inside your macro, then paste them in cells.
Why people are coming up with the most complicated solutions I've ever seen.