如何基于文本编写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 thinksWarlockis a variable name, not the text string you're trying to match. Since you haven't defined aWarlockvariable anywhere, it evaluates toundefined, 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:
- Wrapped class names in single quotes: Changed
Warlockto'Warlock'andFighterto'Fighter'so the script recognizes them as text values to compare against. - Fixed the range reference: Your original code tried to get
Traits!L3from theClasssheet—this was a small bug! I updated it to grab the value from theTraitssheet directly. - Simplified the conditional structure: Switched nested
else { if (...) }to a cleanerelse iffor better readability. - 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
相关产品推荐
相关产品推荐

