简体   繁体   English

比较两个不同单元格的值评估为 false - Google Apps Script

[英]Comparing values of two different cells evaluate to false - Google Apps Script

I'm new with JavaScript and I'm working on a Spreadsheet trying to hide a column base on the cell content.我是 JavaScript 新手,正在处理电子表格,试图根据单元格内容隐藏列。

The idea is: when value 1 and value 2 are the same (the value of two different cells are identical), the column stays as unhidden.想法是:当值 1 和值 2 相同(两个不同单元格的值相同)时,该列保持未隐藏状态。 When is not identical, it hides.当不相同时,它会隐藏。 However, every time OnEdit, the columns hides regardless.但是,每次 OnEdit 时,列都会隐藏。

Also, I can't manage to make it unhide when the values are the same.此外,当值相同时,我无法使其取消隐藏。 Any ideas?有任何想法吗?

 function onEdit(e) { var ss = SpreadsheetApp.getActiveSpreadsheet(); var s = ss.getSheetByName("Auto media planner"); // Enter sheet name var cell1 = s.getRange('C7'); var cell2 = s.getRange('AX6'); var value1 = cell1.getValues(); var value2 = cell2.getValues(); var column = s.getRange("D1"); if (value1!=value2){ s.hideColumn(column); } if (value1==value2){ s.unhideColumn(column); }

Explanation:解释:

  • In your code, value1 and value2 are arrays with the following format [[]] because you use getValues() .在您的代码中, value1value2是具有以下格式[[]]数组,因为您使用了getValues()
  • You can't compare two arrays like you compare two values.不能像比较两个值一样比较两个数组 This value1==value2 returns false even if the values inside the array are the same.即使数组中的值相同,此value1==value2也会返回false
  • To correctly compare two arrays, one way is to run: JSON.stringify(value1)==JSON.stringify(value2) and that will result in true if the value is the same.要正确比较两个数组,一种方法是运行: JSON.stringify(value1)==JSON.stringify(value2)如果值相同,则结果为true

See this example:看这个例子:

 val1 = [[0.0]]; val2 = [[0.0]]; console.log(val1 == val2) // Returns false console.log(JSON.stringify(val1)==JSON.stringify(val2)); // Returns true


Solution:解决方案:

Just replace:只需更换:

var value1 = cell1.getValues();
var value2 = cell2.getValues();

with:和:

var value1 = cell1.getValue();
var value2 = cell2.getValue();

Here is the complete solution:这是完整的解决方案:

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getSheetByName("Auto media planner");      // Enter sheet name
  var cell1 = s.getRange('C7');
  var cell2 = s.getRange('AX6');
  var value1 = cell1.getValue();
  var value2 = cell2.getValue();
  var column = s.getRange("D1");

  if (value1!=value2){  
  s.hideColumn(column);
}
  

if (value1==value2){ 
  s.unhideColumn(column);
} 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM