我有一个带有脚本的电子表格,该脚本会检查另一个电子表格中的客户名称,并返回相关客户的代码。只要客户名称在" CustomerCodes"它引用的表格。如果那里不存在客户名称,我希望它设置变量值" customerCode"到"找不到匹配。"现在它只是抛出一个错误,并且不再运行该脚本。这是代码:
var customerName = sheet.getRange('I2').getValue();
var ccsheet = ss.getSheetByName("CustomerCodes");
var lastRow = ccsheet.getLastRow();
Logger.log("lastRow: " + lastRow);
var lookUp = ccsheet.getRange(2, 1, lastRow, 3).getValues();
for (nn=0; nn<lookUp.length; ++nn) {
if (lookUp[nn][0] == customerName) {break}
}
//This is where I am having the trouble
var customerCode = lookUp[nn][1];
Logger.log("customerCode: " + customerCode);
&#13;
所以,如果&#34; for&#34;循环找到一个匹配,它设置&#34; customerCode&#34;变量到那个匹配。如果它没有找到匹配项,我希望它能够设置&#34; customerCode&#34;变量为&#34;未找到匹配&#34;因此用户知道为什么没有返回客户的代码。变量&#34; customerCode&#34;的值稍后在函数中返回给用户。
我不太了解错误处理,因为我对这一切都很陌生,而且我找不到任何解释得很好的谷歌应用脚本文档。非常感谢你的帮助!
答案 0 :(得分:2)
所以添加代码以查看您是否匹配。其他选项是检查变量nn是否小于长度
var matchIndex = -1;
for (var nn=0; nn<lookUp.length; ++nn) {
if (lookUp[nn][0] == customerName) {
matchIndex=nn;
break;
}
}
//This is where I am having the trouble
var customerCode = matchIndex===-1 ? "Not found" : lookUp[matchIndex][1];
答案 1 :(得分:1)
有关信息,实际上有很多方法可以获得您想要的结果...更简单易读的方法如下:
var customerCode = 'no customer with this ID found in the list';
for (var nn=0; nn<lookUp.length; ++nn) {
if (lookUp[nn][0] == customerName) {
customerCode = lookUp[nn][1];
break;
}
}
当然返回相同的结果,但避免使用上面使用的短格式IF THEN ELSE
语句(也称为三元运算符)。