获取第二个、第三个等等值

Get second, third and so on values

我有这个问题

问题已经解决,但我的问题是如何从中得到第二个值,或者第三个值。 sheet 将有很多 table,在某些时候我需要每个 table 的总数。此外,是否有任何解决方案可以自动找到包含每个 table 的日期行的数组编号(而不是手动定义)。希望我的解释有意义。

谢谢!

亲切的问候,

L.E。 Test file

如果我正确理解了你的问题,而不是在找到与 "Total" 的匹配项时中断循环,而是像这样在循环中做任何需要做的事情...

var today = toDateFormat(new Date());
var todaysColumn = 
    values[5].map(toDateFormat).map(Number).indexOf(+today);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1", 
                                     "dd/MM/yyyy");
for (var i=0; i<values.length; i++){
  if (values[i][0]=='Total'){
    nr = i;
    Logger.log(nr); 

    var output = values[nr][todaysColumn];
    //     Do something with the output here I"m assuming you email it

  }
}

循环将继续寻找每个 "Total" 并做同样的事情。此答案假定 "Totals" 在同一列中。如果您只想发送某些表而不是其他表,您可以使用它来获得更好的体验,但这应该可以帮助您入门。

我不太明白你问题的第二部分...

"Also, is there any solution to automatically find the the array number which contain date row for each table (instead defining this manually). Hope my explanation make sense."

我猜您想要特定列中包含 "Total" 的所有行。您可以像这样将变量实例化为空数组 var totals = [];。然后,不是在第一个循环中发送电子邮件或其他任何内容,而是将行值推送到数组,就像 totals.push(nr+1) . //adding 1 gives you the actual row number (rows count from 1 but arrays count from 0) 一样。然后,您可以简单地遍历总计数组并执行您想执行的任何操作。或者,您可以创建一个包含所有值的数组,而不是像 totals.push(values[nr][todaysColumn]) 这样的行号,然后循环遍历该数组。有很多方法可以解决这个问题!


好的,根据我们下面的对话,我编辑了 "test" sheet 并更新了代码。以下是我的编辑

所有编辑都已在您的测试中进行 sheet 并在 Logger 中验证有效。如果您有任何问题,请告诉我。

传播sheet:

  1. 已添加 "Validation" 选项卡
  2. 编辑了 "Table" 选项卡,使 A 列中带有 "Email Address" 的行与所需的查找值(日期或类别)对齐...这仅适用于前两个表,因为所有其他人已经有了这个标准。

代码: 创建 table/category 选择器...

  1. 在编辑器中转到文件 >> 新建 >> HTML 文件
  2. 将文件命名为 "inputHTML"
  3. 将以下代码复制并粘贴到该文件中

<!DOCTYPE html>
<html>
   <head>
      <base target="_top">
   </head>
   <body>
      <form class="notice_form" autocomplete="off" onsubmit="formSubmit(this)" target="hidden_iframe">
         <select id="tables" onchange="hideunhideCatagory(this.value)" required></select>
         <p></p>
         <select id="categories" style="display:none"></select>
         <hr/>
         <button class="submit" type="submit">Get Total</button>
      </form>
      <script>
         window.addEventListener('load', function() {
         console.log('Page is loaded');
         });
      </script>
      <script
         src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
      <script type="text/javascript">
         // The code in this function runs when the page is loaded.
         $(function() {
         var tableRunner = google.script.run.withSuccessHandler(buildTableList);
         var catagoryRunner = google.script.run.withSuccessHandler(buildCatagoryList);
           
           tableRunner.getTables();
           catagoryRunner.getCategories();
         });
         
         function buildTableList(tables) {
         var list = $('#tables');
         list.empty();
         list.append('<option></option>');
         for (var i = 0; i < tables.length; i++) {
         if(tables[i]==''){break;}
         list.append('<option>' + tables[i] + '</option>');
         }
         }
         
         function buildCatagoryList(categories) {
         var list = $('#categories');
         list.empty();
         list.append('<option></option>');
         for (var i = 0; i < categories.length; i++) {
         if(categories[i]==''){break;}
         list.append('<option>' + categories[i] + '</option>');
         }
         }
         
         function hideunhideCatagory(tableValue){
         var catElem = document.getElementById("categories");
         if(tableValue == "Total Calls By Date" || tableValue == "Total Appointments by Date"){
         catElem.style.display = "none"
         document.required = false;
         }else{
         catElem.style.display = "block"
         document.required = true;
         }
         
         }
         
         function formSubmit(argTheFormElement) {
         
         var table = $("select[id=tables]").val(),
           catagory = $("select[id=categories]").val();
         console.log(table)
         google.script.run
         .withSuccessHandler(google.script.host.close)
         .getTotal(table,catagory);
         }
      </script>
   </body>
   <div id="hiframe" style="display:block; visibility:hidden; float:right"> 
      <iframe name="hidden_iframe" height="0px" width="0px" ></iframe>
   </div>
</html>

编辑到 Code.gs 文件 将 Code.gs 中的代码替换为...

//This is a simple trigger that creates the menu item in your sheet
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Run Scripts Manually')
  .addItem('Get Total','fncOpenMyDialog')
  .addToUi();

}
//This function launches the dialog and is launched by the menu item
function fncOpenMyDialog() {
  //Open a dialog
  var htmlDlg = HtmlService.createHtmlOutputFromFile('inputHTML')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME)
      .setWidth(200)
      .setHeight(150);
  SpreadsheetApp.getUi()
      .showModalDialog(htmlDlg, 'Select table to get total for');
};


//main function called by clicking "Get Total" on the dialogue...variables are passed to this function from the formSubmit in the inputHTML javascript
function getTotal(table,catagory) {
  function toDateFormat(date) {
    try {return date.setHours(0,0,0,0);}
    catch(e) {return;}
  }

  //get all values
  var values = SpreadsheetApp
  .openById("10pB0jDPG8HYolECQ3eg1lrOFjXQ6JRFwQ-llvdE2yuM")
  .getSheetByName("Tables")
  .getDataRange()
  .getValues();

  //declare/instantiate your variables
  var tableHeaderRow, totalRow, tableFound = false;
  //begin loop through column A in Tables Sheet
  for (var i = 0; i<values.length; i++){
    //test to see if values have already been found if so break the loop
    if(tableFound == true){break;}
    //check to see if value matches selected table
    if (values[i][0]==table){
      //start another loop immediately after the match row
      for(var x=i+1; x<values.length; x++){
        if(values[x][0] == "Email Address"){ //This header needs to consistantly denote the row that contains the headers
          tableHeaderRow = x;
          tableFound = true;
        }else if(values[x][0] == "Total"){
          totalRow = x;
          break;
        }
      }
    }
  }

  Logger.log("Header Row = "+tableHeaderRow)
  Logger.log("Total Row = "+ totalRow)
  var today = toDateFormat(new Date())
  var columnToTotal;
  if(catagory==''){
    columnToTotal = values[tableHeaderRow].map(toDateFormat).map(Number).indexOf(+today);
  }else{
    columnToTotal = values[tableHeaderRow].indexOf(catagory);
  }

  var output = values[totalRow][columnToTotal];
  Logger.log(output);
  var emailDate = Utilities.formatDate(new Date(today),"GMT+1", "dd/MM/yyyy");

  //here is where you would put your code to do something with the output

}

/** The functions below are used by the form to populate the selects **/
function getTables(){
  var cFile = SpreadsheetApp.getActive();
  var cSheet = cFile.getSheetByName('Validation');
  var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
  var tabelCol = (cSheetHeader.indexOf("Tables")+1);
  var tables = cSheet.getRange(2,tabelCol,cSheet.getLastRow(),1).getValues();
  return tables.filter(function (elem){
    return elem != "";
  });
}

function getCatagories(){
  var cFile = SpreadsheetApp.getActive();
  var cSheet = cFile.getSheetByName('Validation');
  var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
  var catagoriesCol = (cSheetHeader.indexOf("Catagory")+1);
  var catagories = cSheet.getRange(2,catagoriesCol,cSheet.getLastRow(),1).getValues();
  return catagories.filter(function (elem){
    return elem != "";
  });
}