首页 > 解决方案 > 在 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循环或一个数组,但我对它们的工作方式感到困惑。

标签: google-apps-scriptgoogle-sheets

解决方案


在您的情况下,如何进行以下修改?

修改后的脚本:

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 语句中的脚本就不会运行。我认为这可能是您的问题的原因。

参考:


推荐阅读