1

我正在慢慢地了解如何制定一个通用的编程过程,但我需要一个愿意进一步教我如何钓鱼的人(在这个 JS 池塘中)。

我想测试一系列单元格(例如:A1:A10),如果在该范围内的单元格中找到“,”,我想在该单元格右侧的 5 列单元格中编写一个公式。

到目前为止,我已经能够在指定特定单元格时让它工作,但我不确定如何采用它来处理一系列单元格。

(顺便说一句,这是我理解如何在 VBA 中做的事情 - 尽管没有 SPLIT 功能 - 但这种语言显然是一种非常不同的动物)

这是我现在拥有的:

var defSheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1")   
var test1 = defSheet1.getRange("A1").getValue();
var splitCell = '=SPLIT(A1,",")';
if (test1.indexOf(",") !== -1)  
{
defSheet1.getRange("F1").setFormula(splitCell);
}
 else 
  { 
Browser.msgBox("NO SPLIT NECESSARY");   
  } 

(顺便说一句,实际范围将通过使用 getDataRange 确定,但为简单起见,我在这里使用预先确定的范围)

我已经在这里学到了很多东西,并且我逐渐获得了在 JS 中“思考”的能力,但是 VBA“ For x = 1 to numLastRow ”的概念在 JS 中并不适合我。

4

1 回答 1

0

When you're working on multiple rows and/or columns from spreadsheets, one challenge is converting between indexes and the various ways that cell locations can be expressed.

  • In A1Notation, columns are expressed first, as a letter, followed by row, as a number starting at 1.
  • R1C1 notation flips the order of rows and columns, and both dimensions are numbers starting from 1.
  • Arrays in javascript start from index 0. As you evolve your script to use getDataRange().getValues(), this will be important. In the two-dimensional array returned by getValues(), rows are expressed first, then column, as in data[row][column]. The upper bound of your loops will need to be adjusted accordingly, and you may need to +1 if you're referencing Range methods like setFormula().

The code snippet below will do what you're looking for, as a starting point. I've left out the else block to reduce noise. Note the use of getA1Notation() to build the SPLIT formula dynamically - a straight-forward evolution of your script.

You'll need to define numLastRow yourself, and since the script is accessing Range methods throughout, 10 would mean cell A10.

var defSheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1")

for (var x=1; x<=numLastRow; x++) {
  var srcRange = defSheet1.getRange(x,1);
  var value = srcRange.getValue();  // Get value at Row x, Column 1
  if (value.indexOf(",") !== -1) {
    var splitCell = '=SPLIT(' + srcRange.getA1Notation() + ',",")';
    defSheet1.getRange(x,5).setFormula(splitCell);
  }
}; 
于 2013-04-16T17:28:59.593 回答