Using Google Sheets scripts, why does my if statement always return false when comparing cell values?

后端 未结 2 949
我寻月下人不归
我寻月下人不归 2021-01-15 14:41

I need to compare two cell values and act on them if they are different. My \"if\" statement always returns false when comparing the cell contents however, and I can\'t figu

相关标签:
2条回答
  • 2021-01-15 15:01

    Answer:

    The .getValues() method returns a 2-dimensional array, and so you aren't referencing the values within each cell correctly in your array.

    More Information:

    Let's assume that both A1 and A2 contain the string "THIS". Running the following line:

    var testvalues = sheet.getRange('A1:A2').getValues();
    

    will assign the array [[THIS], [THIS]] to testvalues.

    Code fix:

    You need to change:

    var testvalue1 = testvalues[0]; // The contents from A1
    var testvalue2 = testvalues[1]; // The contents from A2
    

    to:

    var testvalue1 = testvalues[0][0]; // The contents from A1
    var testvalue2 = testvalues[1][0]; // The contents from A2
    

    I hope this is helpful to you!

    References:

    • Class Range | Apps Script - Method getValues()
    0 讨论(0)
  • 2021-01-15 15:07

    The following line of code is incorrect, below it is corrected.

      var testvalue1 = testvalues[0][0]; // The contents from A1
      var testvalue2 = testvalues[1][0]; // The contents from A2
    

    You are originally grabbing the entire row instead of a single cell.

    0 讨论(0)
提交回复
热议问题