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

如何基于文本编写Google Apps Script的if语句?文本匹配失效求助

Fixing the Text Comparison Issue in Your Google Apps Script onEdit Function

Hey there, I spot the exact problem with your code right away! The issue isn't your logic—it's how you're referencing the class names. Let me break it down:

  • When you write char_class == Warlock, the interpreter thinks Warlock is a variable name, not the text string you're trying to match. Since you haven't defined a Warlock variable anywhere, it evaluates to undefined, so your conditional will never be true.
  • Same goes for Fighter—it needs to be treated as a string, not an undefined variable.

Here's the corrected version of your code:

function onEdit() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('Class');
  
  // Make sure the sheet exists to avoid errors
  if (!sheet) return;
  
  var char_class = SpreadsheetApp.getActive().getSheetByName('Traits').getRange('L3').getValue();
  
  if (char_class == 'Warlock') {
    sheet.getRange('A7:D7').breakApart();
    sheet.getRange('A7:D7').mergeAcross();
  } else if (char_class == 'Fighter') {
    sheet.getRange('A7:D7').breakApart();
    sheet.getRange('A7:B7').mergeAcross();
  }
}

Key changes I made:

  1. Wrapped class names in single quotes: Changed Warlock to 'Warlock' and Fighter to 'Fighter' so the script recognizes them as text values to compare against.
  2. Fixed the range reference: Your original code tried to get Traits!L3 from the Class sheet—this was a small bug! I updated it to grab the value from the Traits sheet directly.
  3. Simplified the conditional structure: Switched nested else { if (...) } to a cleaner else if for better readability.
  4. Added a sheet check: Added if (!sheet) return; to prevent errors if the 'Class' sheet doesn't exist.

How it works now:

When the value in Traits!L3 is exactly the text "Warlock", the script will break apart any existing merges in A7:D7 and re-merge the full range. If it's "Fighter", it'll break apart the range and merge only A7:B7 instead.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:13:01