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

后端 未结 2 981
我寻月下人不归
我寻月下人不归 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()

提交回复
热议问题