javascript - 如何在谷歌表格中运行两个单独的函数
问题描述
我想要发生的事情的表格示例:
这个想法是,在第一列中,可以写下物品到达时的名称,这会自动将它到达的日期放在第二列中。然后,当该项目售出时,将记录在第三列中,这会自动将销售日期添加到第四列中。但是,只有第三列有效,而第一列不再输入日期
这是我的代码:
function DateColumnOne() {
var s = SpreadsheetApp.getActiveSheet();
if (s.getName() == "Sheet1") { //checks that we're on Sheet1 or not
var r = s.getActiveCell();
if (r.getColumn() == 1) { //checks that the cell being edited is in column A
var nextCell = r.offset(0, 1);
if (nextCell.getValue() === '') //checks if the adjacent cell is empty or not?
nextCell.setValue(new Date());
}
}
}
function DateColumnTwo() {
var s = SpreadsheetApp.getActiveSheet();
if (s.getName() == "Sheet1") { //checks that we're on Sheet1 or not
var r = s.getActiveCell();
if (r.getColumn() == 3) { //checks that the cell being edited is in column C
var nextCell = r.offset(0, 1);
if (nextCell.getValue() === '') //checks if the adjacent cell is empty or not?
nextCell.setValue(new Date());
}
}
}
如果这个问题已经回答了,请告诉我我应该搜索什么关键字,因为我过去两天尝试自己解决这个问题,但无济于事
解决方案
我认为你需要这样的东西:
function onEdit(e) {
var s = e.source.getActiveSheet();
if (s.getName() != "Sheet1") return;
DateColumnOne(s);
DateColumnTwo(s);
}
function DateColumnOne(s) {
var r = s.getActiveCell();
if (r.getColumn() == 1) { //checks that the cell being edited is in column A
var nextCell = r.offset(0, 1);
if (nextCell.getValue() === '') //checks if the adjacent cell is empty or not?
nextCell.setValue(new Date());
}
}
function DateColumnTwo(s) {
var r = s.getActiveCell();
if (r.getColumn() == 3) { //checks that the cell being edited is in column C
var nextCell = r.offset(0, 1);
if (nextCell.getValue() === '') //checks if the adjacent cell is empty or not?
nextCell.setValue(new Date());
}
}
第一个函数onEdit()
是一个特殊的内部函数,每次手动编辑电子表格时都会触发。
它获取对象e
(名称可以是任何东西)。该对象e
包含有关编辑发生位置的信息。您可以检查此信息(工作表名称等)并运行其他功能。
实际上你可以做的更短。只有一个功能:
function onEdit(e) {
var s = e.source.getActiveSheet(); // get the sheet
if (s.getName() != "Sheet1") return; // check a name of the sheet
var col = e.range.columnStart; // get current column
if (col != 1 && col != 3) return; // check if it's col 1 or 3
var next_cell = s.getActiveCell().offset(0,1); // get next cell
if (next_cell.getValue() != '') return; // check is the cell is empty
next_cell.setValue(new Date()); // fill the cell with current date
}
推荐阅读
- android - 转换数组列表
到 MutableLiveData > 在科特林 - ios - Do i need IOS developer account for React native ios developing
- c++ - 使用 STL 向量的自定义向量容器
- java - 发送不带“根”的 JSON 对象
- php - Laravel 更新间接相关表时抛出无效变量错误
- python - 内含“with open()”的列表理解
- python - 如何在 Python 中使用 opencv 绘制五边形
- verilog - 在 systemverilog 中合成数组操作方法
- python - 如何在滚动的基础上将一列乘以较短的“权重”列表,然后对输出执行计算并存储该值
- sql-server - PII 和非 PII 最终用户的 SQL Server 视图