我正在使用一张包含大约700行的工作表,每一行在第一列上都有一个短语。 我正在尝试编写一个脚本,通过给出一个类似于我所拥有的表 - 将在右边添加一个额外的列,其中包含该行中的单词数,并且在每行上添加计数后,它将对此进行排序根据添加的列按降序排序。
会发生什么事情,显然存在异步性,它首先按第二列排序,然后才增加计数...我环顾四周,无法找到解决这个问题的正确解决方案......任何想法?
代码:
function sortByNumOfKeywords(lang, col, sheet) {
var file = findFileByName("Translate Keywords List");
var spreadsheet = SpreadsheetApp.openById(file.getId());
//Getting the sheet name from the list above
var sheet = findSheetByName(spreadsheet,'Spanish');
//Getting Table bounds (Two-Dimensional array);
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
//add one column (Column H) to hold the number of words of each keyword in the first column
addWordsCounterCol(sheet, col, lastRow, lastColumn);
//sorting by the added column(H)
sheet.sort(8, false);
}
//sets a new column at the end of the table with the number of keywords of each cell in the given Row
function addWordsCounterCol(sheet, col, lastRow, lastCol){
sheet.activate();
var colChar = String.fromCharCode(65 + col-1); //Converts the Col number to it cohherent Big letter
var formulas = []; //Formulas will be set as a two-dimensional array
for(var i=2; i<lastRow+1; i++){
var cell = sheet.getRange("" +colChar + i);
var numOfKeys = "=COUNTA(SPLIT(trim("+ colChar + i + "), \" \"))";
formulas[i-2] = []; //initializing row with a new array
formulas[i-2].push(""+numOfKeys); // each row has only one column, with this specific String
}
var cells = sheet.getRange("H2:H"+(lastRow));
cells.setFormulas(formulas);
}
答案 0 :(得分:1)
尝试使用flush()
。应用所有待处理的电子表格更改。
在您的代码中,它对我来说很好用:
...
SpreadsheetApp.flush();
//sorting by the added column(H)
sheet.sort(8, false);
...