问题
Below is code without an explanation, that i will add later, as SO doesn't like something. I will keep adding to this section until it is happy, and then paste in the actual later. Basically just look for comment lines 'works' and 'fails'... actually, i finally added a comment below, as SO seems to not like it in the body... sorry...
/*
* Sends emails with data from the current spreadsheet.
*/
function sendEmails() {
//var sheet = SpreadsheetApp.getActiveSheet();
var fred = "test";
var sheet = SpreadsheetApp.openById("18ewaD4ruwR5apY4eEFRlO9m2WfgsgwrEgtfEAPqqAeM");
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
//works... var dataRange = sheet.getRange("A2:B3");
//fails... var dataRange = sheet.getRange(startRow, 1, numRows, 2);
var dataRange = sheet.getRange(startRow, 1, numRows, 2);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var subject = 'Sending emails from a Spreadsheet';
MailApp.sendEmail(emailAddress, subject, message);
}
}
One line (marked) works, the other (marked) fails with error:
Exception: The parameters (String,number,number,number) don't match the method signature for SpreadsheetApp.Spreadsheet.getRange. (line 14, file "Code")
The failing one comes right from sample, so not sure WHY it is failing... The spreadsheet contains 3 rows: #1 headings for 2 columns #2 firstemail@gmail.com #3 secondemail@gmail.com
回答1:
Issues:
SpreadsheetApp.openById("id")
is an instance of the Spreadsheet class.
However, getRange
is a method that can be applied to sheet objects.
Solution:
replace:
var sheet = SpreadsheetApp.openById("id");
with any of the following:
var sheet = SpreadsheetApp.openById("id").getSheetByName("sheetName");
var sheet = SpreadsheetApp.openById("id").getActiveSheet();
var sheet = SpreadsheetApp.openById("id").getSheets()[0]; // 0 indicates the 1st sheet
or even with the part that you commented out:
var sheet = SpreadsheetApp.getActiveSheet();
回答2:
You can call getRange() on a Spreadsheet object, but it requires A1 notation.
The getRange(row, column, numRows, numColumns) method is only available on Sheet objects.
来源:https://stackoverflow.com/questions/64037180/getrangestring-works-but-getrangenumber-fails