谷歌表格 - 取消合并单元格并向下填充



我需要拿一张由其他人维护的工作表并执行以下操作(以便我可以导出为 csv(:

  • 取消合并所有单元格
  • 向下填充值
  • 合并的单元格在多列中,所以我需要迭代一个范围

手工完成太多了,需要定期完成。 我的javascript和google工作表对象模型知识接近于零,但我知道这是可能的,因为我可以在VBA中做到这一点。 我搜索了,但只能找到 VBA/Excel 的编程答案。

如何在 Google 表格中有效地执行此操作?

您可以使用breakapart()类来执行此操作。我假设合并的范围不是静态的,并且多次出现。此脚本将取消合并活动工作表中的所有合并范围。

function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()).breakApart();
}

改编自@lreeder的回答

以下在所选范围内中断并填充上述空白:

function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('BreakAndFill')
.addItem('Break Fill Blank Cells', 'menuItem1')
.addToUi();
}
function menuItem1() {
BreakandfillBlankWithAbove()
}
//Breaks range
//Iterates over the range from top to bottom
//and left to right, and fills blank cells 
//with the value right above them.
function BreakandfillBlankWithAbove() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveRange();
Logger.log('Range height is: ' + range.getHeight());
var values = range.getValues();
range.breakApart();
var width = values[0].length;
var height = values.length;
Logger.log('Width is ' + width);
Logger.log('Height is ' + height);
for (var i = 0; i < width; i++) {
var lastVal = '';
for(var j = 0; j < height; j++) {   
var currValue = values[j][i];
var dataType = typeof(currValue);
//Empty string check returns true if dataType
//is a number, and value is zero.  In that case
//we don't want to overwrite the zero, so only
//check emptyString for string types.
if(currValue === undefined || 
(dataType === 'string' && currValue == '')
)  {
//getCell parameters are relative to the current range
//and ones based
var cell = range.getCell(j+1, i+1);
cell.setValue(lastVal);
}
else {
lastVal = currValue;
}
}
}
SpreadsheetApp.flush();
}

最新更新