简体   繁体   中英

I have to google apps script that I want to have the data sorted automatically

I have this script below that imports data automatically from several sheets via a master sheet that has a list of sheet IDs. I would like the data to be auto sorted by a specific column when the data is imported (like by date). Is there a way to do this?

  function customImport() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const inputSheet = ss.getSheetByName('Links');
  const outputSheet = ss.getSheetByName('Master');
  const columnNumberToFilter = 1

  const inputValues = inputSheet.getRange(2, 1, inputSheet.getLastRow() - 1, 3).getValues();
  const output = [];

  inputValues.forEach(entrie => {
    const [url, sheetname, range] = entrie;
    const sheetRange = SpreadsheetApp.openByUrl(url)
      .getSheetByName(sheetname)
      .getRange(range)
    const data = sheetRange.getValues();
    data.forEach(row => {
      if (row[columnNumberToFilter - 1] != "") {
        output.push(row)
      }
    })
  })

outputSheet.getRange(2,1,outputSheet.getLastRow(), outputSheet.getLastColumn()).clearContent();
outputSheet.getRange(2, 1, output.length, output[0].length).setValues(output)
}

Sort by by Date

function sortColByDate(col = 1) {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet0');
  const rg = sh.getDataRange();
  const vs = rg.getValues();
  vs.sort((a, b) => {
    let da = new Date(a[col - 1]).valueOf();
    let db = new Date(b[col - 1]).valueOf();
    return da - db
  })
   sh.getRange(1,1,vs.length,vs[0].length).setValues(vs);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM