編輯電子表格中的行時的日期戳

編輯電子表格中的行時的日期戳

我有一個電子表格,一旦該行中的單元格發生更改,就需要為每一行添加日期戳記。例如,我更改了儲存格 B14、E14 或 G14 上的某些內容,今天的日期出現在 K14 上。顯然,我需要能夠選擇將受到影響的行和列的範圍。

然而,在我的情況下,複雜的一點是我需要今天的日期出現僅有的當我添加或者改變細胞內的訊息。如果我只是刪除來自單元格的資訊我需要日期保持與刪除資訊之前相同。

PS 該文件是 Excel 電子表格,但將在 Google Drive 上使用。

答案1

如果您直接訪問 Google 表格,您就會得到這個答案。

我認為這將有助於讓您朝著正確的方向前進。我不清楚您是否是說您將監視的欄位散佈在工作表周圍,或者您引用的非相鄰儲存格是否只是範圍內的範例。如果單元格散佈在周圍,您可能必須創建多個“監視範圍”,正如我在程式碼中所指出的那樣,並檢查正在編輯的單元格是否在至少一個範圍內,否則從函數中返回。

我想指出的是,我並沒有花費額外的篇幅來支援從多單元格範圍中刪除所有值。

另外,請注意,您必須進入Google Sheet 內的“工具”->“腳本編輯器”,然後進入“資源”->“觸發器”(菜單可能會有所不同,具體取決於您之前在其中所做的操作)並新增“onEdit()”觸發器到工作表。

然後,你的函數將會是這樣的

function onEdit(e){
  var DateCol = "K";
  var DeletedColNote = "L";
  var curDate = Utilities.formatDate(new Date(), "GMT-5", "MM/dd/yyyy") 
  var editRange = e.range;
  var rowIndex = editRange.getRowIndex();
  var colIndex = editRange.getColumnIndex();

  // May need to set up multiple ranges like this and check all ranges if
  // checked fields are not in adjacent cells
  var watchRange = { // B2:G20
    top : 2,         // start row
    bottom : 20,     // end row
    left : 2,        // start col
    right : 7        // end col
  };
  // Exit if we're out of range
  if (rowIndex < watchRange.top || rowIndex > watchRange.bottom) return;
  if (colIndex < watchRange.left || colIndex > watchRange.right) return;

  var currentValue = editRange.getValue();
  currentValue = currentValue.replace(/^\s+|\s+$/g,""); //"trim" kludge

  if (currentValue.length == 0)
  {
    // Set a column to show when data was deleted
    SpreadsheetApp.getActiveSheet().getRange(DeletedColNote + rowIndex).setValue("Deleted: " + curDate);
  }
  else
  {
    // Set a column to show last edit date
    SpreadsheetApp.getActiveSheet().getRange(DateCol + rowIndex).setValue("Edited: " + curDate);
    SpreadsheetApp.getActiveSheet().getRange(DeletedColNote + rowIndex).setValue("");
  }
}

答案2

可惜的是,VBA 無法移植到 Google Sheets,但如果放棄 Google Sheets 要求,使用 VBA 實作起來非常簡單。

將此程式碼附加到感興趣的工作表的 WorkSheet_Change 事件...

Private Sub Worksheet_Change(ByVal Target As Range)
Dim RngToMark As Range
' define the range you want to track changes for
    Set RngToMark = ActiveSheet.Range("A1:G30")
' make sure the change occurred inside the range
    If Intersect(Target, RngToMark) Is Nothing Then Exit Sub
' ignore deleting the contents
    If Target.Value = "" Then Exit Sub
' mark the row as changed
    ActiveSheet.Range("K" & Target.Row).Value = Format(Now(), "MMM-DD-YYYY")

End Sub

要到達正確的位置插入此...

  1. 在 VBEditor 中,按兩下「Microsoft Excel 物件」下的工作表名稱
  2. 然後從左側下拉清單中選擇工作表
  3. 然後從右側下拉選單中選擇“更改”

相關內容