Looking for a way to generate random numbers from 1-9 in cells c2:f2; duplicate values are OK as long as its a number in each cell and the values change only when I click a button or something in that regard, not every time I type something in a cell. Kinda like you can do with Excel and "form control" boxes.
Asked
Active
Viewed 3.8k times
1 Answers
13
Here is a script that will fill each the selected cells with a random number from 1-9. It can be activated from the menu it creates called "Fill random." You should be able to modify it, if needed, to suit your specific requirements:
function numbers19() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveRange();
for (var x = 1; x <= range.getWidth(); x++) {
for (var y = 1; y <= range.getHeight(); y++) {
var number = Math.floor(Math.random() * 8) + 1;
range.getCell(y, x).setValue(number);
}
}
};
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Numbers: 1-9",
functionName : "numbers19"
}];
sheet.addMenu("Fill random", entries);
};
To only change a specific range, use the following value for range
:
var range = sheet.getRange("c2:f2");
-
thanks Tim. what would i edit to automatically generate the numbers in c2:f2 not in cells i select? Thanks – user3079271 Dec 14 '13 at 20:58
-
Awesome, didn't work for me as I only put 'C2:f2' not "c2:f2" – user3079271 Dec 14 '13 at 21:03
-
Would this code not just create numbers 1-8, rather than 1-9 ? – Mad G Jun 11 '16 at 17:41