Скрипт работает на нескольких листах

Я пытаюсь автоматически создать временную метку рядом с ячейкой, которую я редактировал, но по какой-то причине эта временная метка также создается на втором листе. Поэтому, когда я редактирую ячейку на первом листе (под названием "Сезон 8"), она создает временную метку на ячейке рядом с ней, но также создает эту метку времени и на следующем листе (под названием "Alt - Сезон 8"). Кажется, связаны только эти два листа, поскольку временные метки не создаются ни на одном из других листов в документе. Я создал гифку, чтобы показать, в чем проблема: https://imgur.com/a/E5Mp8oB

Вот код:

var ui = SpreadsheetApp.getUi(); //shortcut to access ui methods
var ps = PropertiesService.getScriptProperties(); //shortcut to access properties methods
var ss = SpreadsheetApp.getActiveSpreadsheet() //shortcut to access spreadsheet methods

var timezone = "PST8PDT";
var timestampFormat = "h:mm a, yyyy-MM-dd"; // Timestamp Format (hour:minute, AM/PM, year-month-day)

function timestamp(currentSheet){
  var updateColName = 'Result' //the name of the column we're looking for
  var timestampColName = 'Date' //the name of the column where the timestamp will go
  var sheet = ss.getActiveSheet()
  Logger.log(sheet.getName())

  var actRng = sheet.getActiveRange(); //finding the active range of the selected cell
  var editColumn = actRng.getColumn(); //finding the column of the active cell (returns int, start at index 1)
  var editRow = actRng.getRow(); //finding the row of the active cell

  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues(); //return an array with an element for the value of each cell in the first row (header row)
  var dateCol = headers[0].indexOf(timestampColName, editColumn); //finding the index of the first column after editColumn with the name of timeStampColName (index starts from 0)

  var editColumnName = sheet.getRange(1, editColumn).getValue() //finding the name of the column of the active cell
  if (dateCol > -1 && editRow > 12 && editColumnName == updateColName){ //if: a column with name timestmapColName exists, and if row is below 12, and if the name of the column of the active cell matches the name we are looking for (updateColName), create the timestamp
    var cell = sheet.getRange(editRow, dateCol + 1) //defining which cell the timestamp will go in. We do dateCol + 1 since dateCol starts from index 0, but getRange starts at index 1
    var date = Utilities.formatDate(new Date(), timezone, timestampFormat); //storing our date format in date
    cell.setValue(date); //setting the value of the cell to date (our timestamp)
  }

  Logger.log('first column with header \'Date\': %s', dateCol + 1) //we add 1 to start from index 1 to compare against editColumn which starts at index 1
  Logger.log('column with active cell: %s', editColumn)
  Logger.log('column name of active cell: %s', editColumnName)
  Logger.log('Column name we need to match: %s', updateColName)

}

function onEdit(){
  timestamp()
}

Там нет сценария или пользовательских свойств.

РЕДАКТИРОВАТЬ: У меня есть некоторые обновления, которые полностью сбивают с толку мой разум. Моя теория о том, что эти два листа были связаны каким-то образом, так как второй был сделан с помощью кнопки "Сделать копию", была полностью неверной, как я обнаружил при еще одном тестировании, если ячейки выстроены правильно (расстояние между столбцами) тогда любая временная метка будет создана на активном листе (как и должно быть), а также на любом листе с именем "Сезон 8", если интервал между столбцами правильный. Даже если лист с именем "Сезон 8" является совершенно новым листом, временная метка все равно будет создана. Я понятия не имею, что является причиной этого, и хотел бы выяснить, поскольку мое текущее исправление - просто переименование листа во что-то другое.

0 ответов

Другие вопросы по тегам