mas*_*cip 9 google-sheets google-apps-script
我是第一次使用Google App Script.我在Google Doc电子表格中使用它.
我正在尝试非常简单的功能,只是为了学习基础知识.例如,这有效:
function test_hello() {
return 'hello';
}
Run Code Online (Sandbox Code Playgroud)
但是我对这个简单的问题感到困惑:
function test_today() {
return today();
}
Run Code Online (Sandbox Code Playgroud)
#ERROR!无论我在哪里使用它都能成为现实.当我把光标放在它上面时,它说:
error : ReferenceError: "today" is not defined.
Run Code Online (Sandbox Code Playgroud)
虽然该today()功能在电子表格中直接使用时有效.
这是否意味着在脚本中,我不能使用电子表格内置函数?这周围有什么优雅的方式吗?
一些电子表格函数对我来说非常有用(weekday()例如我喜欢).
一种不优雅的方式可能是创建列来计算我需要的中间值,并且可以使用电子表格函数来计算.但我宁愿避免这些肮脏和笨重的事情.
Google Apps脚本是JavaScript的子集,目前不支持电子表格功能.例如,如果要创建一个返回今天日期的函数,您应该写:
function test_today(){
return new Date()
}// note that this will eventually return a value in milliseconds , you'll have to set the cell format to 'date' or 'time' or both ;-)
Run Code Online (Sandbox Code Playgroud)
语法与表函数相同:=test_today() 请参阅教程
javascript上有很多互联网资源,我找到的最有用的是w3school
Google Apps 脚本仍然不 (1/7/20) 包含 Google Sheets 本机函数的 API。
但是您可以设置电子表格中命名为命名范围的单元格的公式(本机函数)。
然后在气体中:
var nativeOutput = spreadsheet.getRangeByName("outputCell").getValue();
Run Code Online (Sandbox Code Playgroud)
瞧!您的 GAS 正在调用单元中的本机函数。
您可以通过命名工作表(或任何工作表)中由其他单元格中的公式引用的另一个单元格,将数据从 GAS 发送到单元格中的本机函数:
spreadsheet.getRangeByName("inputCell").setValue(inputData);
Run Code Online (Sandbox Code Playgroud)
您的 GAS 可以动态创建这些单元,而不是对它们进行硬编码,例如:
// Create native function, its input and output cells; set input value; use native function's output value:
// Use active spreadsheet.
var spreadsheet = SpreadsheetApp.getActive();
// Name input, output cells as ranges.
spreadsheet.setNamedRange("inputCell", spreadsheet.getRange("tuples!F1"));
spreadsheet.setNamedRange("outputCell", spreadsheet.getRange("tuples!F2"));
var outputCell = spreadsheet.getRangeByName("outputCell");
var inputCell = spreadsheet.getRangeByName("inputCell");
// Set native formula that consumes input cell's value, outputting in formula's cell.
outputCell.setFormula("=WEEKNUM(inputCell)");
// Call native function by setting input cell's value for formula to consume.
// Formula sets its cell's value to formula's output value.
inputCell.setValue(15);
// Consume native function output.
var nativeOutput = outputCell.getValue();
Logger.log("nativeOutput: "+ JSON.stringify(nativeOutput)); // Logs "nativeOutput: 3"
Run Code Online (Sandbox Code Playgroud)
请注意:此技术会公开电子表格用户可以访问/更改的单元格中的代码,并且其他电子表格操作可能会覆盖这些单元格。
| 归档时间: |
|
| 查看次数: |
5565 次 |
| 最近记录: |