You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Google Apps Script不同脚本标签同名函数仅执行第二个的原因咨询

Google Apps Script: Duplicate Function Names Behavior Explained

Question 1: Can you use two functions with the same name in different script tabs?

You technically can write two functions with identical names in separate script tabs, but this is not a valid practice and leads to predictable (but unwanted) behavior. Google Apps Script merges all script files in a project into a single global execution context. Since Apps Script is built on JavaScript, declaring multiple functions with the same name in the global scope results in the last defined function overwriting all previous versions. Even across different tabs, only the final definition of the function will exist when your script runs.

Question 2: Why does only the second myFunction execute, while the first has no effect?

This is a direct result of the overwriting behavior mentioned above. Let’s break down your code:

First function (one tab):

function myFunction() { 
  var SpSheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1'); 
  var Name="Amit" 
  SpSheet.getRange(1,1).setValue(Name); 
}

Second function (another tab):

function myFunction() { 
  var SpSheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet2'); 
  var Name="Amit" 
  SpSheet.getRange(1,1).setValue(Name); 
}

When your project loads, the second myFunction replaces the first one entirely. So whenever you call myFunction (manually, via a trigger, or from a sheet), it’s always the second definition that runs—this is why you only see changes in Sheet2, not Sheet1.

How to Fix This

The straightforward solution is to give each function a unique, descriptive name so they don’t conflict. For example:

// Writes to Sheet1
function writeNameToSheet1() { 
  var SpSheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1'); 
  var Name="Amit" 
  SpSheet.getRange(1,1).setValue(Name); 
}

// Writes to Sheet2
function writeNameToSheet2() { 
  var SpSheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet2'); 
  var Name="Amit" 
  SpSheet.getRange(1,1).setValue(Name); 
}

Now you can call writeNameToSheet1() or writeNameToSheet2() separately, and both will execute as intended.

内容的提问来源于stack exchange,提问作者Amit.S

火山引擎 最新活动