所以我在一个更大的函数中实现了这段代码。基本上,它会搜索隐藏列,将它们隐藏在新形成的工作表中,该工作表将导出为 pdf。发生的情况是,当 columnHidden 为 true 时,每个隐藏列超过 30 时它就会停止。在此之下它工作得很好。
记录器的最后一行和错误:
信息起始列:33,左:58,结束:85,检查列:33,isHidden:false 错误异常:这些列超出范围。
所以它们不能出界,因为它就在中间。
const startColumn = range.getColumn(); // The starting column of the range (e.g., "E" -> 5)
const numColumns = range.getNumColumns(); // The number of columns in the range
for (let i = 0; i < numColumns; i++) {
const originalColumn = startColumn + i; // Get the original column number
const columnHidden = sheet.isColumnHiddenByUser(originalColumn); // Check if the column is hidden in the original sheet
const ende = tempSheet.getLastColumn();
// If the column is hidden in the original sheet, hide the corresponding column in the temporary sheet
if (columnHidden) {
tempSheet.hideColumns(i+1); // Hide the corresponding column in the temporary sheet
}
Logger.log(`start column: ${startColumn + i}, left: ${numColumns-i} , Ende: ${ende} , Checking column: ${originalColumn}, isHidden: ${columnHidden}`) ;
}
我搜索合并的单元格,更改索引,复制粘贴。谷歌了一下,但这不是一个常见问题。问了chatgpt,做了一个测试函数,看看HideColumns在数字超过30时是否有问题(没有)...
根据您的代码,您应该仅将
tempSheet.hideColumns(i+1);
替换为:
tempSheet.hideColumns(originalColumn);
这是带有示例设置的代码:
function test() {
//sample setup
var ss = SpreadsheetApp.getActiveSpreadsheet();
var tempSheet = ss.getSheetByName('Sheet2');
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getRange(1,5,sheet.getLastRow(), sheet.getLastColumn()-4);
var tempSheet = ss.getSheetByName('Sheet2');
var sheet = ss.getSheetByName('Sheet1');
const startColumn = range.getColumn(); // The starting column of the range (e.g., "E" -> 5)
const numColumns = range.getNumColumns(); // The number of columns in the range
for (let i = 0; i < numColumns; i++) {
const originalColumn = startColumn + i; // Get the original column number
const columnHidden = sheet.isColumnHiddenByUser(originalColumn); // Check if the column is hidden in the original sheet
const ende = tempSheet.getLastColumn();
// If the column is hidden in the original sheet, hide the corresponding column in the temporary sheet
if (columnHidden) {
tempSheet.hideColumns(originalColumn); // use original column here
}
// Logger.log(`start column: ${startColumn + i}, left: ${numColumns - i} , Ende: ${ende} , Checking column: ${originalColumn}, isHidden: ${columnHidden}`);
}
}
forEach
和 ternary
的替代代码:function myFunction() {
//sample setup
var ss = SpreadsheetApp.getActiveSpreadsheet();
var tempSheet = ss.getSheetByName('Sheet2');
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getDataRange();
var tempSheet = ss.getSheetByName('Sheet2');
var sheet = ss.getSheetByName('Sheet1');
var startColumn = 5;
//actual edits
var data = range.getValues(); //get the 2d array data to get the dimensions for iteration
data[0].forEach((x, i) => ((i>=startColumn)*(sheet.isColumnHiddenByUser(i + 1)) ? tempSheet.hideColumns(i + 1) : null));
}
上面的代码做了完全相同的事情,并且使用
forEach
和 ternary
的代码缩短了代码的语法。