在多张纸上运行的脚本

时间:2018-07-21 01:18:41

标签: google-apps-script google-sheets triggers google-apps-script-editor

我正在尝试自动在编辑的单元格旁边创建一个时间戳,但是由于某种原因,该时间戳也在第二张工作表上创建。因此,当我在第一张工作表(标题为“第8季”)上编辑一个单元格时,它将在其旁边的单元格上创建一个时间戳,同时也在下一张工作表上创建该时间戳记(标题为“ Alt-Season 8”)。似乎只有这两个工作表是相关的,因为不会在文档中的任何其他工作表上创建时间戳。我创建了一个gif文件来显示问题所在: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的任何工作表上创建任何时间戳。即使名为Season 8的工作表是全新的工作表,仍将创建时间戳记。我不知道是什么原因造成的,我想找出原因,因为我目前的解决方法是将工作表重命名为其他名称。

0 个答案:

没有答案