1
votes

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);
}  
1
If it is a single cell use getValue not getValues ....... var value1 = cell1.getValue(); var value2 = cell2.getValue();arul selvan

1 Answers

1
votes

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