5

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.

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

3 Comments

thanks Tim. what would i edit to automatically generate the numbers in c2:f2 not in cells i select? Thanks
Awesome, didn't work for me as I only put 'C2:f2' not "c2:f2"
Would this code not just create numbers 1-8, rather than 1-9 ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.