Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script to generate random numbers in multiple cells

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.

like image 768
user3079271 Avatar asked Dec 14 '13 19:12

user3079271


1 Answers

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");
like image 86
Tim Cooper Avatar answered Oct 16 '22 02:10

Tim Cooper