首页 > 解决方案 > 用于根据单元格值设置自定义数字格式的 Google Sheet 脚本

问题描述

我想根据同一行中另一个单元格的值将单元格格式化为自定义数字格式。例如,在范围内,A1:U1000我想根据 cell 的文本值格式化单元格J1并使用相同的自定义数字格式。我需要将它传播到几千行。我编辑了一个脚本,我发现它允许我设置我当前选择的单元格的自定义数字格式,但是我希望在编辑列中的值时运行它。我无法将它合并到一个函数中。K1G1GonEdit()

function testV(){
  setNumberFormat('Volume');
}

function testM(){
  setNumberFormat('Mass');
}

function setNumberFormat(format) {
  var range = SpreadsheetApp.getActiveRange();
  var numberFormat = '';
  try {
    switch (format){
      case 'Volume':
        numberFormat = '##0.00,# in³';
        break;
      case 'Mass':
        numberFormat = '##0.00,# g';
        break;
    }
    range.setNumberFormat(numberFormat);
  } catch (e){
    throw new Error('There was an error: ' + e);
  }
}

标签: google-apps-scriptgoogle-sheets

解决方案


我为一个类似的帖子创建了一个触发器,可以在这里重复使用。尝试这个...

function onEdit(e) {
  // set the range to monitor for edits 
  var editRange = {
    top : 5, bottom : 20,                                                     // row numbers in search range
    left : 7, right : 7                                                       // column numbers in search range
  };
  var thisRow = e.range.getRow();                                             // find the row number that was changed
    if(thisRow < editRange.top || thisRow > editRange.bottom) return;         // exit if not in these rows
  var thisColumn = e.range.getColumn();                                       // find the column number that was edited
    if(thisColumn < editRange.left || thisColumn > editRange.right) return;   // exit if not in these columns

  var shtIn = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("stock");  // set the sheet for the cell that will be formatted 
  var numberFormat = '';
  switch(e.value) {
    case 'Mass':
      numberFormat = '##0.00,# g';
      break;
    case 'Volume':
      numberFormat = '##0.00,# in³'
      break;
  }
  shtIn.getRange(thisRow, 10).setNumberFormat(numberFormat);
  shtIn.getRange(thisRow, 11).setNumberFormat(numberFormat);
}

这是一个示例表的链接,希望它可以按您的预期工作。


推荐阅读