谷歌电子表格脚本“切换”隐藏/查看列/行

use*_*517 3 google-sheets google-apps-script

我知道使用这些功能我可以显示和隐藏列:

function showColumns() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  sheet.showColumns(2,3);   // B-D, three columns starting from 2nd 
  sheet.showColumn(7);      //  G, column number 7
}

function hideColumns() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  sheet.hideColumns(2,3);  // B-D, three columns starting from 2nd
  sheet.hideColumn(7);     // G, column 7
}
Run Code Online (Sandbox Code Playgroud)

但为此,我需要两个按钮或菜单脚本,一个用于隐藏,另一个用于显示列。

我想知道是否存在“切换”功能,以便我可以在不需要 2 个按钮或菜单项的情况下激活隐藏/显示功能。

小智 5

我没有看到使用脚本检测列的隐藏/未隐藏状态的方法,但是可以通过将状态存储在Script Properties 中来实现切换行为。这是管理属性并根据需要调用其他两个函数之一的函数。

function toggleColumns() {
  var scriptProperties = PropertiesService.getScriptProperties();
  if (scriptProperties.getProperty('hidden')) {
    showColumns();
    scriptProperties.setProperty('hidden', false); 
  }
  else {
    hideColumns();
    scriptProperties.setProperty('hidden', true);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这不起作用,因为所有属性都存储为字符串,即 false 存储为“false”,这是真的!所以我们最好使用字符串比较。 (2认同)