Google Sheets – Storing Number Produced by RAND Function

google sheetsgoogle-apps-script

In cell B2 I have the formula:

=INT(RAND()*100+1)

Using a script, is there any way I can copy the current results of this RAND function into another cell on the sheet? I want to copy the absolute value, not just mirror the current value.

All attempts I've come up with cause the function to generate a new random number, store that value, then generate yet another random value in cell B2 due to the page being updated.

Ultimately I'd like to click a button that runs a script to store the current value of B2 into another cell.

Best Answer

Using a script, is there any way I can copy the current results of this RAND function into another cell on the sheet?

No, there isn't.

The following script should add the value of B2 to C2, but instead adds a new calculated value.

function freeze1(){
  var s = SpreadsheetApp.getActiveSheet();
  var v = s.getRange("B2").getValue();
  s.getRange("C2").setValue(v);
}

The following script should add the value of B2 to the active range, but it adds a new calculated value

function freeze2(){
  var s = SpreadsheetApp.getActiveSheet();
  var v = s.getRange("B2").getValue();
  var t = SpreadsheetApp.getActiveRange();
  t.setValue(v);
}

On both cases, a third value is calculated "after" the script runs.

An alternative could be the use of a script to calculate the random number instead of a built-in RANDOM() spreadsheet function. The JavaScript command is Math.random().