循环问题

时间:2016-02-18 22:37:53

标签: javascript google-sheets

我完全不熟悉编码(通过培训会计),我试图开发基于答案的表格循环,隐藏或显示另一张表格中存在的一系列数据。我现在手动构建它,但它太慢了,所以我希望我能就如何用循环构建相同的函数得到一些建议。任何帮助将不胜感激。以下示例代码......

//provides code on how to hide or show rows depending on a cell value

function HideRow() { 
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var areas = ss.getSheetByName("areas");
  var Budget = ss.getSheetByName("Budget by Month");

  //REVENUE SECTION

  //provides code on hiding tuition section
  var tuition = areas.getRange('B7').getValue();
  if (tuition == "no"){
    Budget.hideRows(4,6);}
  else {
    Budget.showRows(4,6);
  }
  //provides code on hiding financial aid section
  var aid =areas.getRange('B8').getValue();
  if (aid == "no"){
    Budget.hideRows(10,8);}
  else {
    Budget.showRows(10,8);
  }
  //provides code on hiding student fees section
  var fees =areas.getRange('B9').getValue();
  if (fees == "no"){
    Budget.hideRows(18,16);
  }
  else {
    Budget.showRows(18,16);
  }
}

1 个答案:

答案 0 :(得分:1)

创建循环并不容易,因为rowStart&的值是rowEnd不遵循它看起来的结构。但我设法使它更紧凑和可读;

function HideRow() { 
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var areas = ss.getSheetByName("areas");
  var Budget = ss.getSheetByName("Budget by Month");

  //REVENUE SECTION
  var json = JSON.parse(''); //use my json here

  json.forEach(function(item) {
     if (areas.getRange(item.range).getValue() == "no"){
        Budget.hideRows(item.startRow, item.endRow);
     }
     else {
        Budget.showRows(item.startRow, item.endRow);
     }
  });
}

您可以创建一个JSON对象来存储这些变量,这样它就是一个纯循环逻辑;

[{ "range" : "B7", "startRow" : 4, "endRow" : 6 }, { "range" : "B8", "startRow" : 10, "endRow" : 8 }, { "range" : "B9", "startRow" : 18, "endRow" : 16 }]