合并脚本而不会丢失功能

时间:2019-03-01 19:18:05

标签: google-apps-script google-sheets

我可以运行以下代码以将动态公式添加到列:

function addFormulaSortCol() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("FY 19 Tracker");
  var cell = sheet.getRange("U2:U");

  cell.setFormula(
    "=IF(AND(COUNTA(INDIRECT(ADDRESS(ROW(),1)):INDIRECT(ADDRESS(ROW(),20)))>=1,ISBLANK(INDIRECT(ADDRESS(ROW(),10)))),DATE(1900,1,1),INDIRECT(ADDRESS(ROW(),10)))"
  );
}

我可以运行以下代码对同一选项卡上的记录进行排序:

function sortDocs() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("FY 19 Tracker");
  var range = sheet.getRange("A2:Z500");

  // Sorts by the values in column 21 (U)
  range.sort({ column: 21, ascending: true });
}

然后我合并两个脚本:

function AddColFormulaThenSort() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("FY 19 Tracker");

  var cell = sheet.getRange("U2:U");
  var range = sheet.getRange("A2:Z500");

  // Adds dynamic formula to every cell in column U
  cell.setFormula(
    "=IF(AND(COUNTA(INDIRECT(ADDRESS(ROW(),1)):INDIRECT(ADDRESS(ROW(),20)))>=1,ISBLANK(INDIRECT(ADDRESS(ROW(),10)))),DATE(1900,1,1),INDIRECT(ADDRESS(ROW(),10)))"
  );

  // Sorts by the values in column 21 (U)
  range.sort({ column: 21, ascending: true });
}

此脚本确实执行,但是即使再次运行也不会发生排序。应该如何更新代码以允许这样做?

2 个答案:

答案 0 :(得分:1)

是否有可能在公式有机会评估之前调用排序?

您可以尝试在setFormula部分和sort部分之间添加SpreadsheetApp.flush()

答案 1 :(得分:0)

尝试一下:

function AddColFormulaThenSort() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheet=ss.getSheetByName("FY 19 Tracker");
  var rg1=sheet.getRange("U2:U");
  var fA=rg1.getFormulas();
  for(var i=0;i<fA.length;i++) {
    fA[i][0]="=IF(AND(COUNTA(INDIRECT(ADDRESS(ROW(),1)):INDIRECT(ADDRESS(ROW(),20)))>=1,ISBLANK(INDIRECT(ADDRESS(ROW(),10)))),DATE(1900,1,1),INDIRECT(ADDRESS(ROW(),10)))";
  }
  rg1.setFormulas(fA)
  SpreadsheetApp.flush();
  var rg2=sheet.getRange("A2:Z500");  
  rg2.sort({column: 21, ascending: true});
}