在Google Sheets中将持续时间从文本转换为时间值(例如2小时15分钟到2小时15毫秒)



我有一组正在复制粘贴到工作表上的数据。数据的持续时间列写为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是一个2维数组。这样,您的if语句总是false。这样,if语句中的脚本就不会运行。我想这可能就是你问题的原因。

参考:

  • reduce((

相关内容

最新更新