以下內容應該相當清晰和高效。至少它在工作。 請注意,特別是對於像這樣的簡單模式(一行中的所有單元格),應首先定義範圍,然後在數組中一次選取值。一次選取一個單元格的值明顯較慢。
function myFunction(value1)
{
var cell1 = SpreadsheetApp.getActiveSheet().getRange(value1);
// myFunction("A1") is the same as following:
//cell1 = SpreadsheetApp.getActiveSheet().getRange("A1");
// Define the value here, if it is fixed.
//Otherwise in the function parameters
var columnCount = 6;
// Define the range to get the values from. Parameters:
// Starting row of the range : row of Cell1
// Starting column of the range : column of cell1
// Number of rows = 1
// And the number of columns we wanted
var values = SpreadsheetApp.getActiveSheet()
.getRange(cell1.getRow() , cell1.getColumn() , 1 , columnCount)
.getValues();
// var values == [[ value, value, value, value, value, value ]]
// so actually values[0] is what you requested, the values from A1 to F1
// Now if you want to, for example sum up the values
// You just iterate through the values[0]
var sum = Number(0);
for (var i = 0; i < values[0].length; i++)
{
var cellValue = values[0][i];
sum += Number(cellValue);
}
return sum;
}
請記住,當你調用在電子表格單元格的功能,你不能只是單擊單元格添加參數,因爲它會導致因爲這樣:= myFunction的(A1) - 這樣A1增加了使用單元格A1的值作爲參數。
您需要在調用函數時添加引號,如下所示: = myFunction(「A1」) - 使用單元格作爲參數的方式。
我得到的錯誤是類型錯誤:無法調用的未定義「的getRow」。 (第15行,文件「測試」) –
非常抱歉,發佈時不應該改變尿布,我從代碼中刪除了一行。好的,我更正了代碼。請注意,我將參數名稱更改爲value1並添加了第一行。現在應該工作。 – FatFingersJackson
我現在越來越;錯誤 未找到範圍(第3行)。 它看起來像變量不能被讀爲單元格? –