Monday, August 19, 2013

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

Question:

( 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.


Solution:

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:
http://igoogledrive.blogspot.com/2012/08/how-to-write-script-in-google.html 

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: http://igoogledrive.blogspot.com/2012/09/donate.html 

Thanks,

3 comments:

  1. This is super helpful. Curious how I would disconnect the function from the button if I wanted to make more edits to the script or move the button to a different location?

    ReplyDelete
    Replies
    1. I think it's tools -> script editor, a place where you keep the script and then use it in a spreadsheet. I'm not sure though, I can't get it to work, I have no idea what I'm doing :D

      Delete
  2. Is there a way to use this formula to generate a random integer? Say between .05 and 1.15?

    ReplyDelete