GetValue / SetValue命令+在Google表格文件中执行循环吗?

时间:2018-03-07 18:33:23

标签: javascript for-loop google-apps-script google-sheets

我写了一个' for循环' (见下文)从名为' POTemplate'的标签下的订单输入表中获取值。在我正在使用的Google表格文件中。它似乎得到并设置变量就好了,直到它到达skuNO变量。它将空白单元格值返回到名为POHistory的目标工作表中。

function Submit() {
  var app = SpreadsheetApp;
  var activeSheet = 
app.getActiveSpreadsheet().getSheetByName("POTemplate");
  for(var i = 24; i<= 34; i++) {
    var poNO = activeSheet.getRange("h2").getValue();
    var poDate = activeSheet.getRange("h3").getValue();
    var skuNo = activeSheet.getRange(i, 3).getValue();
    var skuDesc = activeSheet.getRange(i, 4).getValue();
    var qty = activeSheet.getRange(i, 5).getValue();
    var uom = activeSheet.getRange(i, 6).getValue();
    var utCost = activeSheet.getRange(i, 7).getValue();
    var extCost = activeSheet.getRange(i, 8).getValue();
    var targetSheet = 
 app.getActiveSpreadsheet().getSheetByName("POHistory");}
         targetSheet.getRange('a2').setValue(poNO);
         targetSheet.getRange('b2').setValue(poDate);
         targetSheet.getRange('c2').setValue(skuNo);
         targetSheet.getRange('d2').setValue(skuDesc);
         targetSheet.getRange('e2').setValue(qty);
         targetSheet.getRange('f2').setValue(uom);
         targetSheet.getRange('g2').setValue(utCost);
         targetSheet.getRange('h2').setValue(extCost);
}

1 个答案:

答案 0 :(得分:0)

如果您只想复制细胞,copyTo可能会有用。如果您还想添加其他信息,那么appendRow会很有帮助。如果要处理多个单元格,批处理方法getValues()setValues()将非常有用。

var numCols =  8 -  3 + 1;
var numRows = 34 - 24 + 1;
var vals = activeSheet.getRange(24, 3, numRows, numCols).getValues();
/* 
 * vals = [ [skuNo1, skuDesc1, qty1, uom1, utCost1, extCost1],
 *          [skuNo2, ...] ]
 *
 * Add code that does stuff with / to vals, like using 
 * Array.unshift() to insert a value at the start of a given row,
 * or constructing a new array based on vals but with different element orders,
 * some omitted elements, new elements, etc.
 */
var targetColStart = 1; // Column A
var targetRowStart = targetSheet.getLastRow() + 1;
// Select a range having the same size as the `vals` array of arrays.
// (Or whichever array of arrays is to be batch-printed.)
targetSheet.getRange(targetRowStart, targetColStart, vals.length, vals[0].length)
   .setValues(vals);