Need Help with Script that will Randomly select value

49 views
Skip to first unread message

Bill Roberson

unread,
Aug 23, 2022, 2:58:29 PM8/23/22
to Google Apps Script Community
Hello, I  have a Google Sheet with two Sheets in the work sheet. I'd like to make a button that would randomly select a value in a named range on a separate sheet (within the same workbook). How do you write a google script that randomly selects a value from a named range?

Spencer Farris

unread,
Aug 23, 2022, 3:15:18 PM8/23/22
to Google Apps Script Community
let vals = SpreadsheetApp.getActive().getRangeByName(name).getValues() //get all values in the named range
let n = Math.floor(Math.random() * vals.length) -1 //generate a random number between 0 and the length of the array
let val = vals[n][0] //get the value at the random index

Bill Roberson

unread,
Aug 24, 2022, 9:21:26 AM8/24/22
to Google Apps Script Community
Thank you for your help. I am receiving and error that states ReferenceError: RoomNumbers is not defined. In this case, "RoomNumbers" is my named range. Also, it there a piece of code missing that would allow the randomly selected number from the named ranged to display in a certain cell?  https://docs.google.com/spreadsheets/d/1AbgB7yHUDaflbl_GLcx11OR8SRQoucvLoVcYvb9tPNo/edit?usp=sharing 
Reply all
Reply to author
Forward
0 new messages