我需要比较两个单元格值并在它们不同时对其采取行动。然而,在比较单元格内容时,我的“if”语句总是返回 false,我不明白为什么:
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1'); // apply to sheet name only
var testvalues = sheet.getRange('A1:A2').getValues(); // array of values to be tested
var testvalue1 = testvalues[0]; // The contents from A1
var testvalue2 = testvalues[1]; // The contents from A2
var test1 = testvalue1 == testvalue2; // True False test
var test2 = testvalue1 === testvalue2;// True False test
Browser.msgBox(testvalue1 + " and " + testvalue2 + " being the same is " + test1 + " and " + test2); // Sentence revealing outcome
};
无论单元格 A1 和 A2 的内容是什么(空、数字、文本、不同),test1 和 test2 始终返回 false。如果我将测试值编辑为:
var testvalue1 = "We are the same value";
var testvalue2 = "We are the same value";
or
var testvalue1 = testvalues[0];
var testvalue2 = testvalues[0];
然后突然测试都按预期返回 True。谁能告诉我我在这件事上错过了什么,这太令人愤怒了?目前 A1 和 A2 中的值是 1(在我可能被问到这个问题之前)。
最终目标是使用边框来划分不同的单元格内容。我的其余部分工作得很好,但我已将问题与上述概念隔离开来。
Answer:
The .getValues()
方法返回一个二维数组,因此您没有在数组中正确引用每个单元格内的值。
更多信息:
我们假设两者A1
and A2
包含字符串"THIS"
。
运行以下行:
var testvalues = sheet.getRange('A1:A2').getValues();
将分配数组[[THIS], [THIS]]
to testvalues
.
代码修复:
你需要改变:
var testvalue1 = testvalues[0]; // The contents from A1
var testvalue2 = testvalues[1]; // The contents from A2
to:
var testvalue1 = testvalues[0][0]; // The contents from A1
var testvalue2 = testvalues[1][0]; // The contents from A2
参考:
- Class Range| Apps 脚本 - 方法getValues()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)