You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script OnEdit函数条件分支逻辑倒置问题求助

解决Google Apps Script逻辑倒置问题

嘿,我一眼就看出问题出在逻辑运算符的使用上了!你代码里的||(逻辑或)完全搞反了判断逻辑,才导致触发分支和预期颠倒。

问题根源分析

你的原代码中,if分支的条件是:

if (sheet.getSheetName() != "Formulário" || range.getA1Notation() != "D7" || range.getValue() != "Sucesso do Cliente")

这个条件的意思是:只要任意一个条件成立(比如不在Formulário工作表、不是D7单元格、值不是Sucesso do Cliente),就执行该分支的代码。这和你想要的“仅当在Formulário工作表的D7单元格,且值为Sucesso do Cliente时才执行”完全相反!

同理,else if分支的条件也用了||,导致逻辑完全倒置,最终出现了你描述的“值为Sucesso do Cliente时触发错误URL,值为Faturamento时也触发错误URL”的问题。

修正后的代码

我帮你调整了逻辑结构,先过滤掉不符合的情况,再根据目标值执行对应操作,逻辑清晰且不会出错:

function OnEdit(e) { 
  const range = e.range; 
  const sheet = range.getSheet(); 

  // 先过滤:如果不是目标工作表或目标单元格,直接退出函数
  if (sheet.getSheetName() !== "Formulário" || range.getA1Notation() !== "D7") {
    return;
  }

  // 仅在符合条件时,根据单元格值执行对应逻辑
  const cellValue = range.getValue();
  if (cellValue === "Sucesso do Cliente") {
    const url = "https://docs.google.com/spreadsheets/d/1BbuJfPPOSdbvHZ5b8xVTMndeydNfslDhPLm9ftL1pLU/edit?usp=sharing"; 
    const html = `<script>window.open('${url}', '_blank');google.script.host.close();</script>`; 
    SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutput(html), "Carregando..."); 
  } else if (cellValue === "Faturamento") {
    const url = "https://docs.google.com/spreadsheets/d/1o1lKauuBXFTXb2jEEF5t9wAtaYLBPFYu9Y3T_XnO5rk/edit#gid=0"; 
    const html = `<script>window.open('${url}', '_blank');google.script.host.close();</script>`; 
    SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutput(html), "Carregando..."); 
  }
}

代码说明

  • 反向过滤:先判断是否是目标工作表和目标单元格,不符合直接退出,避免后续无效判断,提升代码效率。
  • 正向分支:仅在符合条件时,根据单元格的值匹配对应的URL,逻辑清晰,完全符合你的预期需求。

内容的提问来源于stack exchange,提问作者Melo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 21:57:39