Google apps script 提高应用程序脚本功能的性能,该功能可删除Google工作表中的重复行

Google apps script 提高应用程序脚本功能的性能,该功能可删除Google工作表中的重复行,google-apps-script,google-sheets,Google Apps Script,Google Sheets,我正在寻找优化代码的方法。目前运行需要20分钟 我已经读过“最佳实践”,但我真的不知道如何使用getValues()和setValues() 以下是删除重复行的当前代码: function test(){ var nom_fichier_tlb = "Bloc2021"; var fileId= DriveApp.getFilesByName(nom_fichier_tlb).next().getId(); var sheet = SpreadSheet.open

我正在寻找优化代码的方法。目前运行需要20分钟

我已经读过“最佳实践”,但我真的不知道如何使用
getValues()
setValues()

以下是删除重复行的当前代码:

function test(){
  var nom_fichier_tlb = "Bloc2021";
  var fileId= DriveApp.getFilesByName(nom_fichier_tlb).next().getId();
  var sheet = SpreadSheet.openById(fileId).getSheets()[0];
  var lig = sheet.getLastRow();

  for (var jj = 2;jj<lig;jj++){
    var valVerif1 = sheet.getRange(jj,1).getValue();
    var valVerif2 = sheet.getRange(jj-1,1).getValue();
    if(valVerif1 == valVerif2){
      sheet.deleteRow(jj);
    }
    var valVerif3 = sheet.getRange(jj,4).getValue();

// FonctionsUtiles.right is my equivalent function for Right function in VBA
// FonctionsUtiles.trim is my equivalent function for Trim function in VBA

    if (FonctionsUtiles.right(valVerif3,1) == " "){ 
      sheet.getRange(jj,4) .setValue(FonctionsUtiles.trim(valVerif3));  
    }
    if (valVerif1 == ""){
      var valVerif4 = sheet.getRange(jj+1,1).getValue();
      if (valVerif4 == ""){
        Logger.log("toast");
      }
    }
}
功能测试(){
var nom_fichier_tlb=“bloc021”;
var fileId=DriveApp.getFilesByName(nom_fichier_tlb).next().getId();
var sheet=SpreadSheet.openById(fileId).getSheets()[0];
var lig=sheet.getLastRow();

对于(var jj=2;jj而言,代码运行缓慢,因为它会分别读取每一行。为了加快运行速度,请使用一个
Range.getValues()
调用读取数据,对其进行处理,然后使用一个
Range.setValues()
调用将其写回。这将使代码在几秒钟而不是几分钟内运行

如果您单独格式化了行,并且不想丢失行与其格式之间的关联,请继续使用
Sheet.deleteRow()
,而不是使用
Range.setValues()
,如下所示:

function deleteConsecutiveDuplicateRows() {
  const keyIndex = 0; // column where you want to compare values; zero-indexed -- A = 0, B = 1, C = 2...
  const file = DriveApp.getFilesByName('Bloc2021').next();
  const sheet = SpreadSheet.openById(file).getSheets()[0];
  const data = sheet.getDataRange().getDisplayValues();
  const rowsToDelete = [];
  data.forEach((row, rowIndex) => {
    if (!rowIndex) {
      return;
    }
    const key = row[keyIndex].trim();
    const keyAbove = data[rowIndex - 1][keyIndex].trim();
    if (key && key === keyAbove) {
      rowsToDelete.push(rowIndex + 1);
    }
  });
  deleteRows_(sheet, rowsToDelete);
}

/**
* Deletes from a sheet the rows whose row numbers are given in an array.
*
* @param {SpreadsheetApp.Sheet} sheet A spreadsheet sheet where to delete rows.
* @param {Number[]} rowsToDelete The rows to delete, identified by 1-indexed row numbers.
* @return {Number} The count of delete operations done, i.e., number of the consecutive row runs deleted from the sheet.
*/
function deleteRows_(sheet, rowsToDelete) {
  // version 1.0, written by --Hyde, 23 July 2020
  const runLengths = getRunLengths_(rowsToDelete.sort((a, b) => a - b));
  for (let i = runLengths.length - 1; i >= 0; i--) {
    sheet.deleteRows(runLengths[i][0], runLengths[i][1]);
  }
  return runLengths.length;
}

/**
* Counts consecutive numbers in an array and returns a 2D array that
* lists the first number of each run and the number of items in each run.
*
* The numbers array [1, 2, 3, 5, 8, 9, 11, 12, 13, 5, 4] will get
* the result [[1, 3], [5, 1], [8, 2], [11, 3], [5, 1], [4, 1]].
*
* For best results, sort the numbers array like this:
* const runLengths = getRunLengths_(numbers.sort((a, b) => a - b));
* Note that duplicate values in numbers will give duplicates in result.
*
* @param {Number[]} numbers The numbers to group into runs.
* @return {Number[][]} The numbers grouped into runs, or [] if the array is empty.
*/
function getRunLengths_(numbers) {
  // version 1.1, written by --Hyde, 31 May 2021
  if (!numbers.length) {
    return [];
  }
  return numbers.reduce((accumulator, value, index) => {
    if (!index || value !== 1 + numbers[index - 1]) {
      accumulator.push([value]);
    }
    const lastIndex = accumulator.length - 1;
    accumulator[lastIndex][1] = (accumulator[lastIndex][1] || 0) + 1;
    return accumulator;
  }, []);
}
使用
Sheet.deleteRow()
而不是使用
Range.setValues()
将使代码运行速度变慢,但仍然比当前实现快几倍

不清楚脚本是否绑定到电子表格(即,您通过工具>脚本编辑器在电子表格中输入代码),或者您是否有独立的脚本文件(即,您在驱动器中创建了脚本文件)如果是前者,则不需要使用
DriveApp
调用,但可以使用一个更简单的调用来替换
const file
const sheet
行,该调用将在当前电子表格中获取工作表,如下所示:

function deleteConsecutiveDuplicateRows() {
  const keyIndex = 0; // column where you want to compare values; zero-indexed -- A = 0, B = 1, C = 2...
  const file = DriveApp.getFilesByName('Bloc2021').next();
  const sheet = SpreadSheet.openById(file).getSheets()[0];
  const data = sheet.getDataRange().getDisplayValues();
  const rowsToDelete = [];
  data.forEach((row, rowIndex) => {
    if (!rowIndex) {
      return;
    }
    const key = row[keyIndex].trim();
    const keyAbove = data[rowIndex - 1][keyIndex].trim();
    if (key && key === keyAbove) {
      rowsToDelete.push(rowIndex + 1);
    }
  });
  deleteRows_(sheet, rowsToDelete);
}

/**
* Deletes from a sheet the rows whose row numbers are given in an array.
*
* @param {SpreadsheetApp.Sheet} sheet A spreadsheet sheet where to delete rows.
* @param {Number[]} rowsToDelete The rows to delete, identified by 1-indexed row numbers.
* @return {Number} The count of delete operations done, i.e., number of the consecutive row runs deleted from the sheet.
*/
function deleteRows_(sheet, rowsToDelete) {
  // version 1.0, written by --Hyde, 23 July 2020
  const runLengths = getRunLengths_(rowsToDelete.sort((a, b) => a - b));
  for (let i = runLengths.length - 1; i >= 0; i--) {
    sheet.deleteRows(runLengths[i][0], runLengths[i][1]);
  }
  return runLengths.length;
}

/**
* Counts consecutive numbers in an array and returns a 2D array that
* lists the first number of each run and the number of items in each run.
*
* The numbers array [1, 2, 3, 5, 8, 9, 11, 12, 13, 5, 4] will get
* the result [[1, 3], [5, 1], [8, 2], [11, 3], [5, 1], [4, 1]].
*
* For best results, sort the numbers array like this:
* const runLengths = getRunLengths_(numbers.sort((a, b) => a - b));
* Note that duplicate values in numbers will give duplicates in result.
*
* @param {Number[]} numbers The numbers to group into runs.
* @return {Number[][]} The numbers grouped into runs, or [] if the array is empty.
*/
function getRunLengths_(numbers) {
  // version 1.1, written by --Hyde, 31 May 2021
  if (!numbers.length) {
    return [];
  }
  return numbers.reduce((accumulator, value, index) => {
    if (!index || value !== 1 + numbers[index - 1]) {
      accumulator.push([value]);
    }
    const lastIndex = accumulator.length - 1;
    accumulator[lastIndex][1] = (accumulator[lastIndex][1] || 0) + 1;
    return accumulator;
  }, []);
}

const sheet=SpreadsheetApp.getActiveSheet();

欢迎使用。您当前的代码只删除连续行中的重复行。这就是您想要的吗?行是按A列排序的吗?代码的下半部分似乎多余。请参阅。是的,我的行是按A列排序的,这就是为什么我要删除连续的重复行!好的。我想这是您的第一个问题堆栈交换上的stion。请参阅