在粘贴数组值中导航列和行

时间:2016-10-07 07:48:34

标签: javascript for-loop google-apps-script google-sheets rows

我正在尝试从列A中获取名称列表,随机化列表,然后按用户指定的组数均匀分布(尽可能多,包括来自分区的剩余部分)。

我需要的一个例子就是这样:

名称列表:A,B,C,D,E,F,G,H,I,J,K

3组结果:

  • 第1组:D,A,F
  • 第2组:B,H,G,K
  • 第3组:E,C,I,J

已编辑:我已清理代码:我已将名称列表分配给空数组并成功随机化数组。现在我必须弄清楚如何将这些值粘贴到每个组的各自列中。如何将值粘贴到每列的右侧和下方,同时考虑余数(第一个值是每列的标题):

  • C列:第1组,D,A,F
  • D栏:组2,B,H,G,K
  • E栏:第3组,E,C,I,J

这是我到目前为止所做的:

function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
  .createMenu('Custom Menu')
  .addItem('Show prompt', 'showPrompt')
  .addToUi();
}

function SortNames() {
var ui = SpreadsheetApp.getUi();

var result = ui.prompt(
  'How many groups?',
  ui.ButtonSet.OK_CANCEL);

// Process the user's response.
var button = result.getSelectedButton();
var groupquantity = result.getResponseText();
if (button == ui.Button.OK) {
// User clicked "OK"  - Need to clear the cells from the previous sorting in this step

// Get the last row number of the names list
var Avals = SpreadsheetApp.getActiveSheet().getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;

// Set an empty Array
var ar = [];

/****** In its original order, append the names to the array *****/
for (var i = 2; i < Alast+1; i++) {

  var source = 'A' + i;
  var Avals = SpreadsheetApp.getActiveSheet().getRange(source).getValues();
  ar.push(Avals);
}
/***************************/

/****** Shuffle the array    *****/
function shuffle(a) {
  var j, x, i;
  for (i = a.length; i; i--) {
    j = Math.floor(Math.random() * i);
    x = a[i - 1];
    a[i - 1] = a[j];
    a[j] = x;
  }
}

shuffle(ar);
/***************************/


/****** Calculates the rounded down # of members per group    *****/
var memberspergroup = ar.length / groupquantity;
var memberspergroup = Math.floor(memberspergroup);
/*********************************/



/****** Copy and Paste the rounded down number of members to each groups until 
the remainder is 0, then distribute evenly with remaining number of groups    *****/

// First Cell location to paste
var pasteloc = "C1";
for (var i = 1; i <= groupquantity; i++) {

  SpreadsheetApp.getActiveSheet().getRange(pasteloc).setValue('Group ' + i);
  var source = 'A' + i;
  var Avals = SpreadsheetApp.getActiveSheet().getRange(source).getValues();
}
/*********************************/



} 

else if (button == ui.Button.CANCEL) {
// User clicked "Cancel".
ui.alert('The request has been cancelled');
} 
else if (button == ui.Button.CLOSE) {
// User clicked X in the title bar.
ui.alert('You closed the dialog.');
}

}

1 个答案:

答案 0 :(得分:0)

我找到了问题的解决方案。它不是最好的形状 - 它可以使用改进来计算名称列表中的空单元格。但是,它运行正常,并且做了我想要的所有事情:

  • 它分配数组中的名称列表
  • 随机化数组
  • 完全均匀分布,考虑到余数(就像我上面提供的例子一样)

    function onOpen() {
      SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Custom Menu')
      .addItem('Show prompt', 'showPrompt')
      .addToUi();
    /******closing function onOpen()*********************/
    }
    
    function SortNames() {
      var ui = SpreadsheetApp.getUi();
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
    
      var result = ui.prompt(
        'How many groups?',
      ui.ButtonSet.OK_CANCEL);
    
      // Process the user's response.
      var button = result.getSelectedButton();
      var groupquantity = result.getResponseText();
      if (button == ui.Button.OK) {
      // User clicked "OK"
    
      // Get the last row number of the names list
      var Avalues = sheet.getRange("A1:A").getValues();
      var Alast = Avalues.filter(String).length;
    
        if(groupquantity > 0 && groupquantity <= Alast)
        {
        // User inputted a valid group quantity  - Need to clear the cells from the previous sorting in this step
       var lastRow = SpreadsheetApp.getActiveSheet().getMaxRows();
       sheet.getRange('C1:Z'+lastRow).clearContent();
    
       // Set an empty Array
       var ar = [];
    
       /****** In its original order, append the names to the array *****/
       for (var i = 2; i < Alast+1; i++) {
    
       var source = 'A' + i;
       var Avals = sheet.getRange(source).getValues();
    
       ar.push(Avals);
    
       }
       /***************************/
    
       /****** Shuffles array    *****/
       function shuffle(a) {
         var j, x, i;
         for (i = a.length; i; i--) {
           j = Math.floor(Math.random() * i);
           x = a[i - 1];
           a[i - 1] = a[j];
           a[j] = x;
         }
       /**********closing function shuffle(a)*****************/
       }
    
       shuffle(ar);
    
       /****** Calculates the rounded down # of members per group    *****/
       var memberspergroup = Math.floor(ar.length / groupquantity);
       /*********************************/  
    
    
       /****** Main Goal: Copy and Paste the rounded down number of members to each groups until 
       the remainder is 0, then distribute evenly with remaining number of groups    *****/
       // 1. Define the first Cell location to paste
       var pasteloc = "C1";
    
       // 2. Begin a for-loop: Navigate Horizontally across from the first cell location
       for (var i = 1; i <= groupquantity; i++)
         {
    
           // 3. Set the Column Headings in the current column, i
           sheet.getRange(1,i+2).setValue('Group ' + i);
    
           /************** 4. Fill in the Rows of names for each groups **********/
           // List out the values in array "ar" by the expected group qty, until the remainder is zero
    
           if ((ar.length)%(groupquantity-(i-1)) > 0)
           {
             for (var rows = 2; rows <= memberspergroup+1; rows++)
             {
               var j = 0;
               sheet.getRange(rows,i+2).setValue(ar[j]);
               var index = ar.indexOf(ar[j]);
                ar.splice(index, 1);
             }
    
            }
            else
            {
              var memberspergroup = ar.length/(groupquantity-(i-1))
              for (var rows = 2; rows <= memberspergroup+1; rows++)
              {
               var j = 0;
               sheet.getRange(rows,i+2).setValue(ar[j]);
               var index = ar.indexOf(ar[j]);
               ar.splice(index, 1);
              }
            }
    
         }
       /*********************************/
    
    }
       /*****************closing if(groupquantity > 0 && groupquantity <= Alast)****************/
    
    else{
     ui.alert("Error: " + '"' + groupquantity + '"' +" is not a proper group quantity")
    }
    
    
    
    
       }
    
      else if (button == ui.Button.CANCEL) {
      // User clicked "Cancel".
       }
    else if (button == ui.Button.CLOSE) {
    // User clicked X in the title bar.
     }
    
    
    }
    

我希望这有帮助!