Home > Mobile >  How do I make Google Scripts Compare 2 Variables from a .getvalues in an IF Statement?
How do I make Google Scripts Compare 2 Variables from a .getvalues in an IF Statement?

Time:10-06

I am now using some google Script for a little project, previously I've used VBA but I am no expert by any means at coding.

The situation is this Values2 and Rowd2 are exactly the same, i've tested the if by typing in the exact value in either of their place.

Say for example that they are both "First Name" when debugging they both trigger TRUE on the IF when I compare against "First Name" e.g. [if (values2[i] == "First Name")]

But when I compare them directly I get a FALSE on the IF. I don't get it...

I've tried to use the string filter thing, but no luck :(

This is a really simple issue and I'm sorry to waste your time but I'd really appreciate some help. Code below

 function Messagebox2() {
 var spreadsheet = SpreadsheetApp.getActive();

 var sheet = SpreadsheetApp.getActive().getSheetByName("Comments");


var range = sheet.getRange("Comments!B2:B");
var values = range.getValues();
var values2 = values.filter(String);
var range2 = sheet.getRange("Dashboard!A1")
var rowd = range2.getValues();
var rowd2 = rowd.filter(String);

   
for (var i = 0; i < values2.length; i  ) {
  
 if (values2[i] == rowd2) {
var k = values2[i]

  }
  }

  Logger.log(values2[0]   "   "   k  "    "   rowd2);
}
 

Output is "First Name" undefined "First Name"

CodePudding user response:

The issue comes from the fact that you're comparing arrays of strings instead of the values inside them. sheet.getRange().getValues() returns an array in the form [[column1, column2, ...], ...], even if you only have one column. So the two arrays you're using are similar to the following:

values2 = [["First Name"], ["Second Name"], ...]
rowd = [["First Name"]]

So to make your code work, just change the if statement:

if (values2[i][0] == rowd2[0][0]) {
  var k = values2[i][0]
}

Next time, I would suggest logging the variables individually before you compare them to see if their values are what you think they are. Logging arrays alongside strings converts the arrays into strings, which is why you can't see the brackets in your own log. You can also use typeof.

CodePudding user response:

function Messagebox2() {
  const ss = SpreadsheetApp.getActive();
  const shc = ss.getSheetByName("Comments");
  const shd = ss.getSheetByName('Dashbaord');
  const v2 = shc.getRange(2, 2, shc.getLastRow() - 1, 1).getValues()
  const dba1 = shc.getRange(1, 1).getValue();
  let k = '';
  vs.forEach(r => {
    if (r[0] == dba1) {
      k = r[0];
    }
  });
  Logger.log(v2[0][0]   k   dba1)
}
  • Related