0

Hello I am currently working on a time tracking system. With the following code I track the time how long a value was in a cell. This time is recorded in another worksheet and this is done continuously by appendRow ().

function onEdit(e) {
  addTimestamp(e);
}

function addTimestamp(e) {
  var ui = SpreadsheetApp.getUi();
  var ws = "Tabellenblatt2";
  var ss = e.source;
  var targetSheet = ss.getSheetByName("Tabellenblatt1");
  var range = targetSheet.getRange(3, 2, 1000, 1);
  var currentDate = new Date();
  var scriptProperties = PropertiesService.getScriptProperties();
  if (e.source.getActiveSheet().getName() === ws) {
    var cell = ss.getActiveCell();
    var val = cell.getValue();
    var sourceRowIndex = cell.getRow();
    if (val != "") {
      let rowToAdd = [val, "", currentDate, ""]
      targetSheet.appendRow(rowToAdd);
      scriptProperties.setProperty(sourceRowIndex, targetSheet.getLastRow());
    } else {
      var rowIndex = Number(scriptProperties.getProperty(sourceRowIndex));
      if (rowIndex) targetSheet.getRange(rowIndex, 4).setValue(currentDate);
    }
  }
}

Now one Picture to show my Problem: enter image description here

The problem is that the cells should start in row 1, is that possible with getLastRow ()?

2 Answers2

2

Determine the last row with content based on another column (e.g. column A):

function onEdit(e) {
  addTimestamp(e);
}

function addTimestamp(e) {
  var ui = SpreadsheetApp.getUi();
  var ws = "Tabellenblatt2";
  var ss = e.source;
  var targetSheet = ss.getSheetByName("Tabellenblatt1");
  var range = targetSheet.getRange(3, 2, 1000, 1);
  var currentDate = new Date();
  var scriptProperties = PropertiesService.getScriptProperties();
  if (e.source.getActiveSheet().getName() === ws) {
    var cell = ss.getActiveCell();
    var val = cell.getValue();
    var sourceRowIndex = cell.getRow();
    if (val != "") {
      let rowToAdd = [val, "", currentDate, ""]
      let rowA=targetSheet.getRange("A1:A").getValues().filter(String).length+1; // new code
      targetSheet.getRange(rowA,1,1,rowToAdd.length).setValues([rowToAdd]); // new code
      scriptProperties.setProperty(sourceRowIndex, targetSheet.getLastRow());
    } else {
      var rowIndex = Number(scriptProperties.getProperty(sourceRowIndex));
      if (rowIndex) targetSheet.getRange(rowIndex, 4).setValue(currentDate);
    }
  }
}
Marios
  • 26,333
  • 8
  • 32
  • 52
0

it would be easier to change the formula for Time to not display anything at all unless there was an entry, then getLastRow() will work just fine. For help with that, share the formula that's calculating the time.

MattKing
  • 7,373
  • 8
  • 13