簡體   English   中英

Google Sheet Script - 如果找到單元格值,則返回標頭值

[英]Google Sheet Script - Return header value if cell value found

預先感謝您的幫助。

我有一個包含第一行標題值的Google表格。 我有一個腳本正在查看工作表的其余部分(逐行),如果單元格是某種顏色,則腳本會保持計數。 最后,如果計數數量大於我在工作表中設置的變量,則腳本將觸發電子郵件。

我正在嘗試做的是,如果腳本找到具有設置顏色的單元格,還要捕獲列標題值? 我確定我需要創建一個帶有標題值的數組然后比較位置,我只是不確定如何有效地這樣做。

function sendEmails() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = ss.getSheets()[0];
  var lastRow = dataSheet.getLastRow();
  var lastColumn = dataSheet.getLastColumn();

  //Project Range Information
  var projectRange = dataSheet.getRange(6,3,lastRow-5,lastColumn);
  var projectRangeValues = projectRange.getValues()[0];
  var cellColors = projectRange.getBackgrounds();

  //Student Information Range 
  var studentRange = dataSheet.getRange(6,1,lastRow-5,lastColumn);
  var studentRangeValues = studentRange.getValues();

  //Pull email template information
  var emailSubject = ss.getRange("Variables!B1").getValue(); 
  var emailText = ss.getRange("Variables!B2").getValue();
  var triggerValue = ss.getRange("Variables!B4").getValue();
  var ccValue = ss.getRange("Variables!B5").getValue();

  //Where to Start and What to Check
  var colorY = ss.getRange("Variables!B6").getValue(); 
  var count = 0;
  var startRow = 6;

  //Loop through sheet and pull data
  for(var i = 0; i < cellColors.length; i++) {  
    //Pull some information from the rows to use in email
    var studentName = studentRangeValues[i][0];
    var studentBlogUrl = studentRangeValues[i][1];
    var studentEmail = studentRangeValues[i][2];
    var studentData = [studentName,studentBlogUrl];

    //Loop through cell colors and count them
    for(var j = 0; j < cellColors[0].length ; j++) { 
      if(cellColors[i][j] == colorY) { 

           /*This is where I feel I need to add the array comparisons to get the header values */

           count = count + 1;
      };//end if statement
    };//end for each cell in a row

    //If the count is greater than trigger, send emails
    if (count >= triggerValue) {
        //A call to another function that merges the information              
        var emailBody = fillInTemplateFromObject(emailText, studentData);
        MailApp.sendEmail({
          to: studentEmail,
          cc: ccValue,
          subject: emailSubject,
          htmlBody: emailBody,
        });
    } else {};
    //reset count to 0 before next row
    count = 0;
  };//end for each row
};

編輯:我已根據響應更新了代碼的上述部分:

//Header Information
var headers = dataSheet.getRange(4,4,1,lastColumn);
var headerValues = headers.getValues();
var missingAssignments = new Array();

在for循環中我添加了:

//Loop through cell colors and count them
for(var j = 0; j < cellColors[0].length ; j++) { 
  if(cellColors[i][j] == colorY) {
       //This pushes the correct information into the array that matches up with the columns with a color.
       missingAssignments.push(headervalues[i][j]);
       count = count + 1;
  };//end if statement
};//end for each cell in a row

我遇到的問題是我收到錯誤 - TypeError:無法從undefined中讀取屬性“2”。 這是由於腳本移動到下一行時推入for循環引起的。 我不確定為什么我收到這個錯誤。 從我讀過的其他內容來看,數組設置為undefined。 我試圖將數組設置為空並將其長度設置為0,但它沒有幫助。 我不認為我理解數組的范圍,因為它貫穿始終。

編輯:想出來,“我”不應該迭代。 它應該是:

missingAssignments.push(headervalues[0][j]);

第一個for循環的結束我清除了下一行的數組。

missingAssignments.length = 0;

您應該獲得整個工作表的值。 然后使用shift方法獲取標題。 如果沒有關於工作表的更多信息,我很難完全理解您的意圖。 如果我能提供更多信息,請告訴我。

function sendEmails() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = ss.getSheets()[0];
  var lastRow = dataSheet.getLastRow();
  var lastColumn = dataSheet.getLastColumn();
  //below gets the whole sheet and shifts off the first row as headers
  var fullSheet = dataSheet.getDataRange().getValues();
  var headers = fullSheet.shift();

  //then in your loops you can check against the index of the headers array

使用Apps腳本的電子表格非常慢,特別是如果您有大量數據需要閱讀。

從Apps doc查看以下提示

使用批處理操作

腳本通常需要從電子表格中讀取數據,執行計算,然后將數據結果寫入電子表格。 Google Apps腳本已經有一些內置優化功能,例如使用前瞻性緩存來檢索腳本可能獲取的內容,並編寫緩存以保存可能設置的內容。

您可以通過最小化讀寫次數來編寫腳本以最大限度地利用內置緩存。 交替讀寫命令很慢。 要加速腳本,請使用一個命令將所有數據讀入數組,對陣列中的數據執行任何操作,然后使用一個命令寫出數據。

這是一個例子 - 你不應該遵循或使用的例子。 圖庫中的電子表格分形藝術腳本(僅在舊版Google表格中提供)使用以下代碼設置100 x 100電子表格網格中每個單元格的背景顏色:

// DO NOT USE THIS CODE. It is an example of SLOW, INEFFICIENT code.
// FOR DEMONSTRATION ONLY
var cell = sheet.getRange('a1');
for (var y = 0; y < 100; y++) {
  xcoord = xmin;
  for (var x = 0; x < 100; x++) {
    var c = getColor_(xcoord, ycoord);
    cell.offset(y, x).setBackgroundColor(c);
    xcoord += xincrement;
  }
  ycoord -= yincrement;
  SpreadsheetApp.flush();
}

該腳本效率低下:它循環遍歷100行和100列,連續寫入10,000個單元格。 Google Apps腳本回寫緩存會有所幫助,因為它會強制在每行末尾使用flush進行回寫。 由於緩存,只有100個電子表格調用。

但是通過批量調用可以使代碼更加高效。 這是一個重寫,其中單元格區域被讀入一個名為colors的數組,顏色分配操作對數組中的數據執行,並且數組中的值被寫出到電子表格:

// OKAY TO USE THIS EXAMPLE or code based on it.
var cell = sheet.getRange('a1');
var colors = new Array(100);
for (var y = 0; y < 100; y++) {
  xcoord = xmin;
  colors[y] = new Array(100);
  for (var x = 0; x < 100; x++) {
    colors[y][x] = getColor_(xcoord, ycoord);
    xcoord += xincrement;
  }
  ycoord -= yincrement;
}

  sheet.getRange(1, 1, 100, 100).setBackgroundColors(colors); 

效率低下的代碼大約需要70秒才能運行。 高效的代碼只需1秒鍾即可運行!

如果您正在查看電子表格分形藝術腳本(僅適用於舊版Google表格),請注意我們對其進行了微小更改,以使此示例更易於理解。 發布的腳本使用setBackgroundRGB調用,而不是上面看到的setBackgroundColor。 getColor_函數更改如下:

if (iteration == max_iteration) {
   return '#000000';
} else {
   var c = 255 - (iteration * 5);
   c = Math.min(255, Math.max(0, c));
   var hex = Number(c).toString(16);
   while (hex.length < 2)
     hex = '0' + hex;

   return ('#' + hex + '3280');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM