繁体   English   中英

Google 表格 - 时间戳和 clearContent

[英]Google Sheets - Time Stamps and clearContent

我正在尝试创建一个谷歌表格系统,供人们用来帮助​​跟踪他们的日常活动。 我们目前每天都在手写这个。 我最初在 excel 上创建了一个类似的,但我需要它可以被多人在多个系统上使用,所以我将它移动到谷歌表。

我目前无法弄清楚的是,当第 1 列中的信息被删除(在 A5 和 A55 之间)时,如何在行上正确使用 clearContents。

简而言之,当单元格 A6 被删除时,我想在第 6 行的其余部分使用 clearConents,但是当在 A6 中输入数据时,它会将时间填充到第 6 行的不同单元格中。

function onEdit(e) {
  var sheet      = e.source.getActiveSheet();
  var activeCell = sheet.getActiveCell();
  var col        = activeCell.getColumn();
  var row        = activeCell.getRow();
  
  
  //Start Time Function
  if (col == 1 && isBlank){   // These first two rows are what I cannot figure out.
    sheet.getRange(row).clearContent();
  }
   else if (col == 1){
    sheet.getRange(row, col+11).setValue(new Date()).setNumberFormat('hh:mm:ss');
    sheet.getRange(row,col+13).setValue(new Date()).setNumberFormat('hhmm');
    sheet.getRange(row, col+5).setValue(new Date()).setNumberFormat('hhmm');
    sheet.getRange(row, col+3).setValue(new Date()).setNumberFormat();
   }
  
  
  //End Time Function
  if (col == 8) {
    sheet.getRange(row, col+5).setValue(new Date()).setNumberFormat('hh:mm:ss');
    sheet.getRange(row, col+7).setValue(new Date()).setNumberFormat('hhmm');
    sheet.getRange(row, col-1).setValue(new Date()).setNumberFormat('hhmm');
  }
} 

修改

根据其他答案,您的工作代码可以通过以下修改进行优化:

  1. onEdit触发器事件对象有一个range属性,您可以使用它来代替getActiveCellonEdit ,建议使用getCurrentCell代替)。
  2. 使用批处理方法(如setValuessetNumberFormats )并对内存中的对象进行修改。 调用 I/O(输入/输出)方法(如循环或重复调用getRangesetValue )很慢。
  3. 使用带有===类型安全比较。 为什么? 看看这个:

 console.log( 0 == "" ); console.log( [] == "" ); console.log( 0 === "" ); console.log( [] === "" );

应用所有修改后,您的脚本将变为以下内容:

function onEdit({
  source,
  range: currRng
}) {

  var sheet = source.getActiveSheet();

  var col = currRng.getColumn();
  var row = currRng.getRow();
  var val = currRng.getValue();

  const maxRows = sheet.getMaxRows();
  const maxCols = sheet.getMaxColumns();

  const range = sheet.getRange(1, 1, maxRows, maxCols);

  const values = range.getValues();

  const formats = range.getNumberFormats();

  const now = new Date();
  const hhmmssFormat = "hh:mm:ss";
  const hhmmFormat = "hhmm";

  const colIdx = col - 1;
  const rowIdx = row - 1;

  //Start Time Function
  if (col === 1 && row >= 5 && row <= 55 && val === "") {
    sheet.getRange(row, 1, 1, maxCols).clearContent();
  } else if (col === 1) {

    const newValues = values.map((row, ri) => {
      if (ri === rowIdx) {
        row[colIdx + 11] = now;
        row[colIdx + 13] = now;
        row[colIdx + 5] = now;
        row[colIdx + 3] = now;
      }
      return row;
    });

    const newFormats = formats.map((row, ri) => {
      if (ri === rowIdx) {
        row[colIdx + 11] = hhmmssFormat;
        row[colIdx + 13] = hhmmFormat;
        row[colIdx + 5] = hhmmFormat;
        row[colIdx + 3] = hhmmFormat;
      }
      return row;
    });

    range.setValues(newValues);
    range.setNumberFormats(newFormats);

    console.log(range.getValues()[14]);
    console.log(range.getNumberFormats()[14]);
  }

  //End Time Function
  if (col === 8) {

    const newValues = values.map(row => {
      row[colIdx + 5] = now;
      row[colIdx + 7] = now;
      row[colIdx - 1] = now;
      return row;
    });

    const newFormats = formats.map(row => {
      row[colIdx + 5] = hhmmssFormat;
      row[colIdx + 7] = hhmmFormat;
      row[colIdx - 1] = hhmmFormat;
      return row;
    });

    range.setValues(newValues);
    range.setNumberFormats(newFormats);
  }
}

您必须启用V8 运行时才能使上述工作正常运行。


使用模拟的工作片段:

 function Range({ sheet, grid, row = 1, column = 1, numRows = 1, numColumns = 1 }) { const intRow = row - 1; const intCol = column - 1; /** @type {function (any[][], function)} */ const sliceMap = (g, row, col, rows, cols, mapper) => g.slice(row, row + rows).map( (r) => r.slice(intCol, col + cols).map(mapper) ); /** @type {function (any[][], any[][], number, number, string)} */ const sliceUpdate = (g, ug, row, col, prop) => g.forEach( (r, ri) => r.forEach((c, ci) => { if (ri < row || ci < col) { return; } const arow = ri - row; const acol = ci - col; g[ri][ci][prop] = ug[arow][acol]; }) ); return { activate() { sheet.setActiveRange(this); return this; }, clearContent() { grid.forEach((r, ri) => r.forEach((c, ci) => { ri >= intRow && ci >= intCol && (grid[ri][ci].value = ""); })); return this; }, getCell(row, column) { return Range({ sheet, grid, row: row + intRow, column: column + intCol }); }, getColumn() { return column; }, getFormulas() { return sliceMap(grid, numRows, numColumns, ({ formula }) => formula); }, setFormulas(formulas) { sliceUpdate(grid, formulas, intRow, intCol, "formula"); return this; }, getNumberFormats() { return sliceMap(grid, intRow, intCol, numRows, numColumns, ({ format }) => format); }, setNumberFormats(numberFormats) { sliceUpdate(grid, numberFormats, intRow, intCol, "format"); return this; }, getRow() { return row; }, getValue() { const [val] = sliceMap(grid, intRow, intCol, numRows, numColumns, ({ value }) => value); return val[0]; }, getValues() { return sliceMap(grid, intRow, intCol, numRows, numColumns, ({ value }) => value); }, setValues(values) { sliceUpdate(grid, values, intRow, intCol, "value"); return this; } }; } function Sheet(spreadsheet) { /** @type {{ value }[][]} */ const grid = []; let sheetName = "Sheet1"; let active = null; return { activate() { spreadsheet.setActiveSheet(this); return this; }, getCurrentCell() { return active && active.getCell( active.getRow(), active.getColumn() ); }, getDataRange() { return Range({ grid, sheet: this }); }, getLastRow() { return grid.findIndex(row => row.some(({ value }) => value !== "")) + 1 || 1; }, getLastColumn() { const lasts = grid.map(row => row.reverse().findIndex(({ value }) => value !== "") + 1); return Math.max(...lasts) || 1; }, getMaxColumns() { return grid[0].length; }, getMaxRows() { return grid.length; }, getRange(row, column, numRows = 1, numColumns = 1) { return Range({ grid, sheet: this, row, column, numRows, numColumns }); }, getSheetName() { return sheetName; }, insertColumns(columnIndex, numColumns) { grid.forEach(row => { const cols = new Array(numColumns).fill("") .map(() => ({ value: "", formula: "", format: "" })); row.splice(columnIndex, 0, ...cols); }); return this; }, insertRows(rowIndex, numRows) { const rows = new Array(numRows).fill("") .map(() => [{ value: "", formula: "", format: "" }]); grid.splice(rowIndex, 0, ...rows); return this; }, setActiveRange(range) { active = range; return this; }, setName(name) { sheetName = name; return this; } }; } function Spreadsheet() { const defaultSheet = Sheet(this); const sheets = [defaultSheet]; let active = defaultSheet; return { getSheets() { return sheets; }, getActiveSheet() { return active; }, insertSheet(sheetIndex = 0) { const sheet = Sheet(this); sheets.splice(sheetIndex, 0, sheet); return sheet.activate(); }, setActiveSheet(sheet) { active = sheet; return sheet; } }; } var SpreadsheetApp = { getActiveSpreadsheet() { return Spreadsheet(); } }; function onEdit({ source, range: currRng }) { var sheet = source.getActiveSheet(); var col = currRng.getColumn(); var row = currRng.getRow(); var val = currRng.getValue(); const maxRows = sheet.getMaxRows(); const maxCols = sheet.getMaxColumns(); const range = sheet.getRange(1, 1, maxRows, maxCols); const values = range.getValues(); const formats = range.getNumberFormats(); const now = new Date(); const hhmmssFormat = "hh:mm:ss"; const hhmmFormat = "hhmm"; const colIdx = col - 1; const rowIdx = row - 1; //Start Time Function if (col === 1 && row >= 5 && row <= 55 && val === "") { sheet.getRange(row, 1, 1, maxCols).clearContent(); } else if (col === 1) { const newValues = values.map((row, ri) => { if (ri === rowIdx) { row[colIdx + 11] = now; row[colIdx + 13] = now; row[colIdx + 5] = now; row[colIdx + 3] = now; } return row; }); const newFormats = formats.map((row, ri) => { if (ri === rowIdx) { row[colIdx + 11] = hhmmssFormat; row[colIdx + 13] = hhmmFormat; row[colIdx + 5] = hhmmFormat; row[colIdx + 3] = hhmmFormat; } return row; }); range.setValues(newValues); range.setNumberFormats(newFormats); console.log(range.getValues()[14]); console.log(range.getNumberFormats()[14]); } //End Time Function if (col === 8) { const newValues = values.map(row => { row[colIdx + 5] = now; row[colIdx + 7] = now; row[colIdx - 1] = now; return row; }); const newFormats = formats.map(row => { row[colIdx + 5] = hhmmssFormat; row[colIdx + 7] = hhmmFormat; row[colIdx - 1] = hhmmFormat; return row; }); range.setValues(newValues); range.setNumberFormats(newFormats); } } //Test: (() => { const ss = SpreadsheetApp.getActiveSpreadsheet(); const sh = ss.getActiveSheet(); sh.insertRows(0, 55); sh.insertColumns(0, 13); const rng = sh.getRange(1, 1, sh.getMaxRows(), sh.getMaxColumns()); rng.activate(); const vals = rng.getValues(); vals[14][0] = "val"; rng.setValues(vals); onEdit({ source: ss, range: sh.getRange(15, 1) }); })();

解释:

你很亲近。 本质上,您需要像这样修改第一个 if 条件:

if (col == 1 && row>=5 && row<=55 && sheet.getRange(row,col).getValue() == "")
  • col == 1 :必须编辑 A 列中的单元格
  • row >=5<=55 :必须编辑 A5 和 A55 之间的单元格。
  • value == "" :您清除了它的值。

如果上述条件评估为真,则清除整行:

sheet.getRange(row,1,1,sheet.getMaxColumns()).clearContent();

解决方案:

function onEdit(e) {
  var sheet      = e.source.getActiveSheet();
  var activeCell = sheet.getActiveCell();
  var col        = activeCell.getColumn();
  var row        = activeCell.getRow();
  
  //Start Time Function
  if (col == 1 && row>=5 && row<=55 && sheet.getRange(row,col).getValue() == ""){ 
    sheet.getRange(row,1,1,sheet.getMaxColumns()).clearContent();
  }
    else if (col == 1){
    sheet.getRange(row, col+11).setValue(new Date()).setNumberFormat('hh:mm:ss');
    sheet.getRange(row,col+13).setValue(new Date()).setNumberFormat('hhmm');
    sheet.getRange(row, col+5).setValue(new Date()).setNumberFormat('hhmm');
    sheet.getRange(row, col+3).setValue(new Date()).setNumberFormat('hhmm');
   }
  
  //End Time Function
  if (col == 8) {
    sheet.getRange(row, col+5).setValue(new Date()).setNumberFormat('hh:mm:ss');
    sheet.getRange(row, col+7).setValue(new Date()).setNumberFormat('hhmm');
    sheet.getRange(row, col-1).setValue(new Date()).setNumberFormat('hhmm');
  }
} 

参考:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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