简体   繁体   中英

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.

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. When is not identical, it hides. However, every time OnEdit, the columns hides regardless.

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() .
  • 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.
  • 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.

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);
} 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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