本文介绍了使用 Google 表格脚本,为什么我的 if 语句在比较单元格值时总是返回 false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要比较两个单元格值并在它们不同时对它们进行操作.我的如果"但是,在比较单元格内容时,语句总是返回 false,我不知道为什么:

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 figure out why:

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Sheet1'); // apply to sheet name only
  var testvalues = sheet.getRange('A1:A2').getValues(); // array of values to be tested
  var testvalue1 = testvalues[0]; // The contents from A1
  var testvalue2 = testvalues[1]; // The contents from A2
  var test1 = testvalue1 == testvalue2; // True False test
  var test2 = testvalue1 === testvalue2;// True False test
  Browser.msgBox(testvalue1 + " and " + testvalue2 + " being the same is " + test1 + " and " + test2); // Sentence revealing outcome
};

无论单元格 A1 和 A2 的内容是什么(空、数字、文本、不同),test1 和 test2 总是返回 false.如果我将测试值编辑为此:

test1 and test2 always return false no matter what the contents of cell A1 and A2 are (empty, number, text, different). If I edit the testvalues to this:

  var testvalue1 = "We are the same value";
  var testvalue2 = "We are the same value";

  var testvalue1 = testvalues[0];
  var testvalue2 = testvalues[0];

然后突然测试都按预期返回 True .谁能告诉我我在这件事中缺少什么,这很令人生气吗?目前在 A1 和 A2 中的值为 1(在我可能被问到之前).

then suddenly the tests both return True as expected. Can anyone tell me what I'm missing in this, it's infuriating? Currently in A1 and A2 is the value 1 (before I potentially get asked about that).

最终目标是使用边框来划分不同的单元格内容.我的其余部分工作正常,但我已将问题与上述概念隔离开来.

The end goal is to use a border to partition different cell contents. I have the rest of it working perfectly but I've isolated the problem to the above concept.

推荐答案

答案:

.getValues() 方法返回一个二维数组,因此您没有正确引用数组中每个单元格中的值.

Answer:

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

假设 A1A2 都包含字符串 THIS".运行以下行:

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

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

会将数组 [[THIS], [THIS]] 分配给 testvalues.

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

你需要改变:

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

到:

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

参考资料:

  • Range |Apps 脚本 - 方法 getValues()
  • References:

    • Class Range | Apps Script - Method getValues()
    • 这篇关于使用 Google 表格脚本,为什么我的 if 语句在比较单元格值时总是返回 false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 05:04