Monday, August 19, 2013

Google Spreadsheet Script How to: Make a button that generates random number?


( by ChielScape )

Specifically for the purpose of the RAND() function. I'm trying to create dice-rolling functionality.
What kind of script do I need for this? My scripting/programming skills/knowledge are 0.


To have a button, you can insert an image which looks like a button.
To insert image, go to: "Insert" > "Image".
And then you can click on the on the small arrow on that image which will show you option of "Assign script..." and then put the custom function "rollDice" and then click "OK".
And then you can click on this so called button to generate the random number between 1 to 6 and display it on any desired cell.

Have a look at the following animated screenshot:

Have a look at the following code:


function onOpen() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [ {name:"Roll Dice",functionName:"rollDice"} ];
  sheet.addMenu("Script", entries);

function rollDice() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1");
  var cell = sheet.getRange("C3");
  cell.setValue( Math.floor((Math.random()*6)+1) );



put the above code in your script editor, and then you can use it directly in your Google Spreadsheet.

Click on the button "ROLL THE DICE", then script will generate it and display it on Cell "C3" of "Sheet1".

You can set the cell and sheet as per your requirement.

And If you are not much familiar with scripts then check out the following link: 

I hope the above solution will help you, and if you need more help then please do comment below on this blog itself, I will try to help you out.

I also take up private and confidential projects:
If this blog post was helpful to you, and if you think you want to help me too and make my this blog survive then please donate here: 


No comments:

Post a Comment