Google Sheets: Hiding Columns based on date in row 1

≡放荡痞女 提交于 2019-12-02 09:36:32

Because you don't have a "database like" source it will be very difficult, but you can try create a very complicated

QUERY()

you should filter the dates in another sheet (and you may face a dead end).

So I will suggest to use this kind of structure and it will also allow you to make other kind of filters (or Pivot Tables) in the future (maintainable and scalable).

With Apps Script via Tools->Script Editor, you could create a menu with an onOpen() function. The function in the menu (e.g. hidePast), would then need to check a given value in each column (to see what date that column refers to), and then flag it to be hidden or not. The onOpen function, because it is a "simple trigger", cannot do anything that requires "authorization" (such as interacting with non-local Spreadsheet data), hence the intermediate method. By creating a menu, you can make it easy for anyone using the spreadsheet to authorize and activate the function.

Example:

/* @OnlyCurrentDoc */
function onOpen() {
    SpreadsheetApp.getActive().addMenu("Date Tools",
        [{name:"Hide Past", functionName:"hidePast"},
         {name:"Show All", functionName:"showAll"}]);
}
function showAll() {
    var ss = SpreadsheetApp.getActive();
    var sheet = ss.getActiveSheet();
    sheet.unhideColumn(sheet.getDataRange());
    ss.toast("All columns unhidden.");
}
function hidePast() {
    var ss = SpreadsheetApp.getActive();
    var sheet = ss.getActiveSheet();
    // Acquire the 1st row of all used columns as an array of arrays.
    var datelist = sheet.getSheetValues(1, 1, 1, sheet.getLastColumn());

    // Drop the hours, minutes, seconds, etc. from today.
    var now = new Date();
    var today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));

    // Inspect the datelist and compare to today. Start from the rightmost
    // column (assuming the dates are chronologically increasing).
    var col = datelist[0].length;
    while(--col >= 0) {
        var then = new Date(datelist[0][col]);
        if(then < today) {
            break;
        }
    }

    // Bounds check, and convert col into a 1-base index (instead of 0-base).
    if(++col < 1) return;

    // col now is the first index where the date is before today.
    // Increment again, as these are 2-column merged regions (and
    // the value is stored in the leftmost range). If not incremented,
    // (i.e. hiding only part of a merged range), spreadsheet errors will occur.
    sheet.hideColumn(sheet.getRange(1, 1, 1, ++col));
    ss.toast("Hid all the columns before today.");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!