简体   繁体   中英

Get random range google spreadsheet

I have managed with VBA and Excel to achieve my purposes, but I'd like to move to google spreadsheet for particular reasons.

I'm trying to replicate a code that works just fine in VBA.

It's simple, I have a sheet with a bank of questions in column A, and I'd like a macro that can select 1 random question and copy it to a second sheet.

I'm having trouble understanding how I can access a random cell, copy it and paste it to the second sheet. Some plain explanation would be appreciated since I have very little or non-existent knowledge of programming or javascript.

function test() {
  var ss = SpreadsheetApp.openById("sheetID");

  //Say I have 10 questions in the BANKSHEET, for instance
  var rQuestion = Math.floor(Math.random()*10+1); 

  //What goes in A1? So that I can access the range randomly according to rQuestion value.
  var inputRange =  ss.getSheetByName("BANKSHEET").getRange("A1");
  var inputValues = inputRange.getValues();
  var outputRange = ss.getSheetByName("QUIZZ").getRange("A1").setValues(inputValues);

How about this modification? I think that there are several solutions for your situation. So please think of this as one of them.

Modification points :

  • Retrieve the number of cells at "A1:A" from sheet of "BANKSHEET".
  • Retrieve randomly one of the number.
  • Copy the cell value of the retrieved number to "A1" of "QUIZZ".

Modified script :

function test() {
  var ss = SpreadsheetApp.openById("sheetID");

  // Retrieve randomly a value from sheet of BANKSHEET
  var sheet = ss.getSheetByName("BANKSHEET");
  var src = sheet.getRange("A" + (1 + Math.floor(Math.random() * sheet.getLastRow())));

  // Put the value to "A1" at sheet of QUIZZ
  var dst = ss.getSheetByName("QUIZZ").getRange("A1");
  src.copyTo(dst);
}

Note :

  • It supposes that there are values in only column A of "BANKSHEET".
  • This modified script randomly retrieves one value from column A of "BANKSHEET" every time.
    • If you don't want to use the value which has already been used, please modify the script for your situation.

Reference :

If I misunderstand your question, I'm sorry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM