google-apps-script - 在 Google 表格中将持续时间从文本转换为时间值(例如 2 小时 15 分钟到 2 小时 15 分 0 秒)
问题描述
我有一组数据被复制粘贴到一张纸上。数据有一个持续时间列,写为 X h X min。但是,这些值不会被识别为数值,因此数据不能用于任何计算。我找到了一个 onEdit 脚本,可以将文本更改为适当的时间值,但只有在我逐个编辑每个单元格时它才会起作用。
有没有办法用一个可以用按钮触发的脚本替换这个脚本,而不是每次编辑单元格时?
function onEdit(e) {
var value = e.value;
if (typeof value == 'string') {
var match = value.match(/(\d+) ?h/i);
var hours = match ? match[1] : 0;
match = value.match(/(\d+) ?m/i);
var minutes = match ? match[1] : 0;
match = value.match(/(\d+) ?s/i);
var seconds = match ? match[1] : 0;
if (hours || minutes || seconds) {
var duration = hours/24 + minutes/1440 + seconds/86400;
e.range.setValue(duration).setNumberFormat('[h]"h "m"m "s"s"');
}
}
}
我尝试了以下方法,但它不起作用:
function setDuration(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var value = sheet.getRange("C45:C80").getValues();
if (typeof value == 'string') {
var match = value.match(/(\d+) ?h/i);
var hours = match ? match[1] : 0;
match = value.match(/(\d+) ?m/i);
var minutes = match ? match[1] : 0;
match = value.match(/(\d+) ?s/i);
var seconds = match ? match[1] : 0;
if (hours || minutes || seconds) {
var duration = hours/24 + minutes/1440 + seconds/86400;
range.setValues(duration).setNumberFormat('[h]"h "m"m "s"s"');
}
}
}
我很难理解 onEdit 脚本的工作原理。我知道我需要设置一个for
循环或一个数组,但我对它们的工作方式感到困惑。
解决方案
在您的情况下,如何进行以下修改?
修改后的脚本:
function setDuration(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = sheet.getRange("C45:C80");
var values = range.getValues();
var formats = range.getNumberFormats();
var {converted, format} = values.reduce((o, [value], i) => {
if (typeof value == 'string') {
var match = value.match(/(\d+) ?h/i);
var hours = match ? match[1] : 0;
match = value.match(/(\d+) ?m/i);
var minutes = match ? match[1] : 0;
match = value.match(/(\d+) ?s/i);
var seconds = match ? match[1] : 0;
if (hours || minutes || seconds) {
var duration = hours/24 + minutes/1440 + seconds/86400;
o.converted.push([duration])
o.format.push(['[h]"h "m"m "s"s"']);
} else {
o.converted.push([value]);
o.format.push(formats[i]);
}
} else {
o.converted.push([value]);
o.format.push(formats[i]);
}
return o;
}, {converted: [], format: []});
range.setValues(converted).setNumberFormats(format);
}
在此修改中,用于将字符串转换为日期和数字格式的脚本将复制到单元格中。
在您的脚本中,
value
是一个二维数组。这样,您的 if 语句始终是false
. 这样,您的 if 语句中的脚本就不会运行。我认为这可能是您的问题的原因。
参考:
推荐阅读
- flutter - firestore 邮政限制
- php - 在 Laravel 5.8 中使用会话传递可变数据
- c# - 在哪里下载 EntityFramework 的 System.Data.Objects.DLL
- c++ - 如何使用 __LINE__ 或其他方法从呼叫站点获取行号?
- angular - 使用打字稿在 foreach 循环中进行递归的正确方法是什么?
- javascript - 谁能告诉我为什么我在 try 块中的 setTimeout 函数不起作用?
- python - 列表中的 Python dicts,显示按 dictkey 分组的最高分
- xslt - 使用 xslt 将 xml 转换为 html 列表
- android - 在通道 plugins.it_nomads.com/flutter_secure_storage 上找不到方法写入的实现
- amazon-web-services - AWS cli 创建没有 appspec 文件的部署