脚本改组单元格值而不是公式

Script shuffles cell values instead of formulas

我得到了以下代码,可以使用脚本随机排列多个列。

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('SheetToShuffle');
  var ranges = ['A1:A32','B1:B47','C1:C39','D1:D87'];

  ranges.forEach(r => shuffleColumns(r, sheet));

function shuffleColumns(r, sheet) {
  var range = sheet.getRange(r);
  range.setValues(shuffleArray(range.getValues()));  
}

问题是它打乱了单元格的值而不是公式。有没有办法改变这个?我想让它打乱单元格,以将公式保留在单元格中。

我想我可以这样做:

function main() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName('SheetToShuffle');
  const ranges = ['A1:A32','B1:B47','C1:C39','D1:D87'];
  ranges.forEach(r => shuffleColumn(r, sheet));
}

function shuffleColumn(rng,sheet) {
  const range    = sheet.getRange(rng);
  const col      = range.getColumn();
  const values   = range.getValues().flat();
  const formulas = range.getFormulas().flat();

  // get indexes and suffle them
  const indexes = shuffleArray(values.map((_,i) => i));

  // order the values by the indexes and put them on the sheet
  range.setValues(indexes.map(i => [values[i]]));

  // order the formulas by the indexes and put them on the sheet
  indexes.map(i => formulas[i]).forEach((frm,row) =>
    { if (frm) sheet.getRange(row+1, col).setFormula(frm) });
}

// 
function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

代码随机排列包含值和公式的单元格。

更新

如果您的范围只有公式,函数 shuffleColumn() 可以更短并且更有效:

function shuffleColumn(rng,sheet) {
  const range = sheet.getRange(rng);
  const formulas = range.getFormulas().flat();

  // get indexes and suffle them
  const indexes = shuffleArray(formulas.map((_,i) => i));

  // order the formulas by the indexes and put them on the sheet
  range.setFormulas(indexes.map(i => [formulas[i]]));
}