我正在使用 Google Apps 脚本,并且正在尝试编写一个程序来合并我的每月笔记。我隐藏了 i-t 列,它们按时间顺序标记为“2024 年 1 月”-“2024 年 12 月”。我在 H 列中配置了一个下拉列表,显示“2024 年 1 月”-“2024 年 12 月”可供选择。
这个想法是隐藏 12 个月的笔记(在纸上看起来很糟糕),并让我取消隐藏我选择的单个列。下拉列表中的“2024 年 1 月”,应取消隐藏名为“2024 年 1 月”的列。
由于某种原因它没有做任何事情。不知道该怎么办。
这是代码:
function onEdit(e) {
// Ensure the function only runs during actual edits
if (!e) return; // If no event object (e), stop the execution to avoid errors
var sheet = e.source.getActiveSheet();
// Ensure the edit was made in column H (8th column) and after the header row
if (e.range.getColumn() == 8 && e.range.getRow() > 1) {
var selectedMonth = e.range.getValue(); // Get the value of the selected month
// Define the mapping of months to columns
var monthMapping = {
"January 2024": 9, // Column I
"February 2024": 10, // Column J
"March 2024": 11, // Column K
"April 2024": 12, // Column L
"May 2024": 13, // Column M
"June 2024": 14, // Column N
"July 2024": 15, // Column O
"August 2024": 16, // Column P
"September 2024": 17,// Column Q
"October 2024": 18, // Column R
"November 2024": 19, // Column S
"December 2024": 20 // Column T
};
// Notes columns from I to T (9 to 20)
var notesColumnStart = 9;
var notesEndColumn = 20;
// Unhide all columns from I to T
sheet.showColumns(notesColumnStart, notesEndColumn - notesColumnStart + 1);
// Check if the selected month exists in the mapping
if (selectedMonth in monthMapping) {
var selectedColumn = monthMapping[selectedMonth]; // Get the corresponding column number
// Check if the selected column is already visible
var isColumnVisible = !sheet.isColumnHiddenByUser(selectedColumn);
if (isColumnVisible) {
// If the column is visible, re-hide it (toggle behavior)
sheet.hideColumns(selectedColumn);
Logger.log("Hiding column: " + selectedColumn);
} else {
// If the column is hidden, show it and hide all others
Logger.log("Showing column: " + selectedColumn);
for (var col = notesColumnStart; col <= notesEndColumn; col++) {
if (col !== selectedColumn) {
sheet.hideColumns(col); // Hide the column if it is not the selected month
}
}
sheet.showColumns(selectedColumn); // Make sure the selected column is shown
}
} else {
// If the selected month isn't in the mapping, log the issue
Logger.log("Month not found in the mapping: " + selectedMonth);
}
}
}
你的代码已经差不多了,我重构并删除了不需要的不必要的代码行。
你可以试试这个:
function onEdit(e) {
var sheet = SpreadsheetApp.getActive().getActiveSheet();
// Define the mapping of months to columns
var monthMapping = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
// Notes columns from I to T (9 to 20)
var notesColumnStart = 9;
var notesEndColumn = 20;
// Hide all columns from I to T
sheet.hideColumns(notesColumnStart, notesEndColumn - notesColumnStart + 1);
// Trigger Event
if (e.range.getColumn() == 8 && e.range.getRow() == 1) {
const date = e.range.getValue().getMonth();
// console.log();
sheet.showColumns(monthMapping[date]);
}
}
示例输出:
参考: