You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:将Excel VBA添加行功能转换为Google Apps Script

解决Google Sheets批量取消指定数量隐藏行并调整行高的问题

以下是完善后的Google Apps Script代码,完全匹配你的需求:

function unhideRowsAndAdjustHeight() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const maxUnhide = 20;
  const minUnhide = 1;
  const targetStartRow = 27;
  const targetEndRow = 56;
  const targetRowHeight = 20; // 可根据需要调整行高值

  // 弹出输入框获取用户输入的行数
  const userInput = SpreadsheetApp.getUi().prompt(
    '取消隐藏行数',
    `请输入要取消隐藏的行数(${minUnhide}-${maxUnhide}):`,
    SpreadsheetApp.getUi().ButtonSet.OK_CANCEL
  );

  // 处理用户取消操作
  if (userInput.getSelectedButton() === SpreadsheetApp.getUi().Button.CANCEL) {
    return;
  }

  // 验证输入有效性
  const rowCount = parseInt(userInput.getResponseText());
  if (isNaN(rowCount) || rowCount < minUnhide || rowCount > maxUnhide) {
    SpreadsheetApp.getUi().alert(`请输入${minUnhide}到${maxUnhide}之间的有效数字!`);
    return;
  }

  let unhiddenCount = 0;

  // 遍历目标行范围,查找并取消指定数量的隐藏行
  for (let i = targetStartRow; i <= targetEndRow && unhiddenCount < rowCount; i++) {
    if (sheet.isRowHidden(i)) {
      sheet.unhideRow(sheet.getRange(i, 1));
      sheet.setRowHeight(i, targetRowHeight);
      unhiddenCount++;
    }
  }

  // 如果目标范围内隐藏行不足,提示用户
  if (unhiddenCount < rowCount) {
    SpreadsheetApp.getUi().alert(`仅找到${unhiddenCount}个隐藏行,已全部取消隐藏!`);
  }
}

代码说明:

  • 输入验证:严格限制用户输入1-20的有效数字,不符合条件时弹出提示
  • 遍历逻辑:从第27行到56行依次检查,遇到隐藏行就取消隐藏并设置行高,直到达到用户指定的数量
  • 边界处理:如果目标范围内隐藏行数量少于用户输入的数量,会弹出提示告知实际取消的行数
  • 可配置项:targetRowHeight可按需调整行高数值,targetStartRow和targetEndRow可修改目标行范围

使用方法:

  1. 打开目标Google Sheets文件
  2. 点击菜单栏「扩展程序」→「Apps 脚本」
  3. 替换原有代码为上述代码并保存
  4. 首次运行需完成授权操作
  5. 返回表格后,可通过「扩展程序」调用该函数,或添加绘图按钮绑定函数实现点击触发

内容的提问来源于stack exchange,提问作者Tommy Smothers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:39:57