微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Google Apps脚本根据列的条件使行在Google表格中不可编辑

如何解决使用Google Apps脚本根据列的条件使行在Google表格中不可编辑

我有一个Google表格,其中将包含员工更新的历史数据。我想冻结(不可编辑)具有从一月到七月的数据(直到上个月)的行,并保留当前月份的行进行编辑。每行都有一个列,其中包含“月”。任何月份为1月至7月(直到上个月)的行,都应对其进行保护以进行编辑。我曾尝试使用数据验证,但是任何有权访问工作表的人都可以将其删除

以下是示例工作表:https://docs.google.com/spreadsheets/d/102Rs93sZxeY2rq1WJEIL50P_6RLRzOCmDlIH6ZoBTx8/edit#gid=0

解决方法

解决方案:

这是您要寻找的:

function protectData() {
  
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const today_date = new Date();
  const today_month = today_date.toLocaleString('default',{ month: 'short' });
  const today_full_date = `${today_month}-${today_date.getFullYear()}`
  const months = sh.getRange('C2:C'+sh.getLastRow()).getDisplayValues().flat(1);
  const protection = sh.protect();
   
  const unprotected = [sh.getRange(sh.getLastRow()+1,1,sh.getMaxRows()-sh.getLastRow(),sh.getMaxColumns()),sh.getRange(1,sh.getLastColumn()+1,sh.getMaxRows(),sh.getMaxColumns()-sh.getLastColumn())];
  
  months.forEach((month,index)=>{          
                 if(month===today_full_date)
                       {                    
                          unprotected.push(sh.getRange(index+2,sh.getLastColumn()));                                           
                       }           
                 })
    protection.setUnprotectedRanges(unprotected);                
}

说明:

以下是步骤:

  1. Jan-2020的格式获取今天的月份年份,
  2. 获取 C列的所有日期值,
  3. 保护完整工作表,
  4. 反复浏览C列的日期值:如果今天的月年与日期值匹配,请取消保护该行。

结果:

只有包含2020年8月的行才能被编辑(不受保护):

result

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。