Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

google apps script - How do I restrict a trigger to a specific sheet/tab?

I have written a script in google sheets that will change the time stamp in the selected cell anytime the entire spreadsheet is updated at all. However, I need the timestamp to only update when one single sheet(tab) is updated. Here is my current function:

function onEdit() {
  var sheetActive = SpreadsheetApp.getActiveSpreadsheet()
    .getSheetByName("Board")
    .getRange('A28')
    .setValue(new Date());
}

The name of the sheet(tab) that I want to check for an update in is "Input" and the specific cell in the tab is A1 if that matters.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The onEdit trigger triggers whenever any sheet/tab is edited. It cannot be restricted to a single sheet. However, even if it is triggered, it is possible to make it do nothing with a simple if and testing the event object that is sent on each edit, which contains the circumstances of the edit made.

Sample:

/**
 * @param {GoogleAppsScript.Events.SheetsOnEdit} param1
 */
function onEdit({ range: /*edited range*/ eRange }) {
  const restrictCell = 'A1',
    restrictToSheet = 'Input';
  if (
    eRange.getA1Notation() !== restrictCell ||
    eRange.getSheet().getName() !== restrictToSheet
  )
    return;
  SpreadsheetApp.getActiveSpreadsheet()
    .getSheetByName('Board')
    .getRange('A28')
    .setValue(new Date());
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...