2015-02-09 44 views
1

我試圖使我的Google表單每次有人填寫表單時都會通過電子郵件向我發送表單內容。我正在使用下面的說明,並且我完全遵循了它們。然而,出於某種原因,當我填寫表單時,出現「TypeError:Can not call method」getRange「爲空的錯誤(第7行,文件」代碼「)」Google表單腳本發送電子郵件故障

我看了代碼正上方,其中定義了「s」,我在想,問題在於getActiveSpreadsheet由於某種原因無法正常工作。我認爲腳本可能找不到活動工作表。根據我從google獲得的錯誤電子郵件,下面是導致問題的代碼片斷。

var s = SpreadsheetApp.getActiveSheet(); 
    var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];  

我正在使用的整段代碼;

function sendFormByEmail(e) 
{  
    // Remember to replace this email address with your own email address 
    var email = "[email protected]"; 

    var s = SpreadsheetApp.getActiveSheet(); 
    var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];  
    var message = ""; 
    var subject = "Jones IT - New User Form"; 

    // The variable e holds all the form values in an array. 
    // Loop through the array and append values to the body. 

    for(var i in headers) 
    message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";  

    // Insert variables from the spreadsheet into the subject. 
    // In this case, I wanted the new hire's name and start date as part of the 
    // email subject. These are the 3rd and 16th columns in my form. 
    // This creates an email subject like "New Hire: Jane Doe - starts 4/23/2013" 
    subject += e.namedValues[headers[1]].toString() + " - starts " + e.namedValues[headers[2]].toString(); 

    // Send the email 
    MailApp.sendEmail(email, subject, message); 

} 

回答

0

您收到錯誤的原因是因爲代碼是從綁定到表單的腳本項目運行的,而不是電子表格。綁定到表單的腳本沒有與電子表格的連接。它找不到活動工作表。沒有與表單關聯的活動工作表。該表格與電子表格關聯的位置與提交數據的位置相關,但與代碼無關。您可以在電子表格中設置觸發器,以便在提交表單時運行,但您可能希望按ID獲取電子表格。

function test() { 

    var s = SpreadsheetApp.openById('your SS ID'); 
    var sheet = s.getSheetByName('your sheet name'); 
    var headers = sheet.getRange(1,1,1,s.getLastColumn()).getValues()[0]; 

}; 
+0

糟糕,第一次在這個網站上,我把我的評論作爲答案,我的壞。我還有一個問題,如果你要回答它,但它不適合在這個評論框中,所以我發佈它作爲答案。 – 2015-02-17 19:55:54

1

好的,謝謝,這是有道理的,但當我改變我的代碼使用該代碼段時,我得到這個錯誤。

2/12/15 4:56 PM sendFormByEmail TypeError:無法調用方法「getRange」 null。 (第9行,文件「代碼」)formSubmit 2/12/15 4:56 PM

第9行是sheet.getRange()函數調用的行。

var s = SpreadsheetApp.openById('1WYhDQct8vF-3rlca9dP6lYC2Z23vLLofwJt_DpQU--c'); 
    var sheet = s.getSheetByName('Jones IT - New User Form (Responses)'); 
    var headers = sheet.getRange(1,1,1,s.getLastColumn()).getValues()[0]; 

有沒有什麼辦法可以推薦我更改我的代碼以獲得所需的結果。我並不在乎我必須改變什麼,我只是希望它在提交時向我發送表格內容。

+0

您的變量'sheet'爲空。 'getRange()'是一種方法,試圖用在對'sheet'的引用上。你的代碼來獲取'sheet'是正確的。所以,我不可能知道真正的錯誤是什麼。我所能做的只是猜測。也許它不喜歡這個名字:'瓊斯IT - 新用戶表單(回覆)'我不知道。也許你的電子表格ID是錯誤的?它必須是這兩件事中的一件。使用調試器來遍歷代碼。打開此鏈接:[Apps Script Debugger](https://developers.google.com/apps-script/troubleshooting#using_the_debugger_and_breakpoints) – 2015-02-17 20:10:27

相關問題