如何在Google Apps脚本中正确使用设置范围并获取范围功能?

时间:2019-01-02 09:12:59

标签: google-apps-script

仅当“ order sku”等于“ product sku”时,我才需要基于“ order数量”的值来更新“ product数量”的值。

function productLoop2() {

  var app = SpreadsheetApp;
  var ss = app.getActiveSpreadsheet();
  var activeSheet = ss.getActiveSheet();

  var t = 2;
  var n = 2;
  var s = 0;

  for(var t = 2; t < 52; t++) {
    var x = activeSheet.getRange(t, 1).getValue();
    //x is the ORDER SKU
    var r = activeSheet.getRange(t, 2).getValue();
   //r is the ORDER QUANTITY
    var q = activeSheet.getRange(n, 3).getValue();
    //q is the PRODUCT SKU  
    var u = activeSheet.getRange(n, 4).getValue();
    //u is the PRODUCT QUANTITY

    if (x != q) {
    n++;
    } else {
      s = u - r;
    }
      var m = activeSheet.getRange(n,4).setValue(s);
  }  

}

我需要更新单元格“ n,4”(订购数量),以便该值等于“ u”(产品数量)减去“ r”(订购数量)的结果

2 个答案:

答案 0 :(得分:1)

代码“ if”片段应按以下方式更正:

if (x != q) {
  n++;
} else {
  activeSheet.getRange(n,4).setValue(u - r);
}

讨论后更新:

function updateProductQuantities() {
  var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var values = activeSheet.getDataRange().getValues();

  // Sum quantities by orders (columns A and B)
  var sku = {};
  for (var i in values) {
    if (i == 0) continue;  // headers row
    if (sku[values[i][0]] == undefined) {
      sku[values[i][0]] = values[i][1];
    } else {
      sku[values[i][0]] += values[i][1];
    }
  }

  // Update product quantities (columns C and D)
  for (i in values) {
    if (sku[values[i][2]] != undefined) {
      values[i][3] -= sku[values[i][2]];
    }
  }

  // return values to the sheet
  activeSheet.getDataRange().setValues(values);
}

您应该使用2个“ for”循环。一种是订单数量之和,另一种是减法。

答案 1 :(得分:1)

您可以在此处获取所有数据,对其进行修改并在工作表中设置

func main() {
data, _ := ioutil.ReadFile("/opt/tests/req.txt")
fmt.Print(string(data))
}

参考文献:

Multidimensional arrays

Best practices - batch operations

For loops