google-apps-script - 用于根据单元格值设置自定义数字格式的 Google Sheet 脚本
问题描述
我想根据同一行中另一个单元格的值将单元格格式化为自定义数字格式。例如,在范围内,A1:U1000
我想根据 cell 的文本值格式化单元格J1
并使用相同的自定义数字格式。我需要将它传播到几千行。我编辑了一个脚本,我发现它允许我设置我当前选择的单元格的自定义数字格式,但是我希望在编辑列中的值时运行它。我无法将它合并到一个函数中。K1
G1
G
onEdit()
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);
}
}
解决方案
我为一个类似的帖子创建了一个触发器,可以在这里重复使用。尝试这个...
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);
}
这是一个示例表的链接,希望它可以按您的预期工作。
推荐阅读
- javascript - 如何通过 Google 进行身份验证并重定向到 Cordova 应用程序?
- typescript - VSCode 调试器和 Typescript:Step Over/Into 转到 JS 文件
- json - 如何避免在 Sequel 中序列化 postgres json 结果
- ruby-on-rails - 如何创建动态 csv 导出文件?
- r - 如何批量传递多个 id 并将其合并到 R
- c# - 如何从 Calendly 获取现有的 webhook(从 json 解析)?
- python - 在 csv 文本中查找单词
- mysql - 无法打开 mysql-workbench
- excel - 为 3 个电子表格中不匹配的特定行 ID 创建表输出
- excel - DAX Error: Expressions that yield variant data-type cannot be used to define calculated columns