google-apps-script - 试图将现有脚本限制为特定工作表
问题描述
我的第一个问题是,我有一个项目日志表,我想在其中添加和管理我们库存中的单个独特项目。我为主要类别创建了一个数据验证相关下拉列表,并了解了如何构建脚本以根据所选主要类别动态创建次要类别下拉列表。
例如:如果单元格 B2(主类别)设置为登山扣(基于另一张工作表上的数据验证范围),那么单元格 C2(次要类别)将动态创建相对于登山扣主类别的下拉列表(即锁定、非锁定)
如果您只有一行来创建下拉列表,那就很简单了,但是我希望能够从每一行的次要类别列表中进行选择,具体取决于在主类别单元格中选择的类别。
我找到了一个脚本的视频,它做到了这一点并且让它工作得很好。
现在的问题是脚本在每个其他工作表上运行数据验证。如何将脚本限制为仅在特定工作表上运行?
这是脚本:
function onEdit() {
// this line just refers to the current file var start = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var current = start.getActiveCell()
// var to refer to the worksheets -lists is where the data validation range will come from, and main is where we want to use that data validation range var list = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Indirect_Categ_Ranges") var main = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Items_Log");
// has the user selected a category? Refers to the column number in the Items_Log sheet where the user has picked the main category
if (current.getColumn()==2)
{
//to copy the selected sub-category -the 2,1 is the row and column on the Indirect_Categ_Ranges sheet where this script will dynamically update the main category picked to define what the indirect function will display in the next column
var choice = current.getValue()
list.getRange(2,1).setValue(choice)
//clear any validation -the 2,3,1000 looks to start clearing validation at row 2, column 3 and down for up to 1000 entries
main.getRange(2,3,5000).clearDataValidations()
// create the rule - var_point defines the offset number of rows and columns to shift to initiate the dynamic dependent dropdown list, the var_items defines where the to look for the range to build the dropdown list
var point = current.offset(0,1)
var items = list.getRange(2,2,50)
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(items,true).build();
point.setDataValidation(rule)
}
}
此外,无论有多少行,有没有办法运行清晰的验证?
解决方案
只要有编辑,该功能就会运行,您无法阻止它。相反,如果它不是您关心的工作表,您可以先发制人地终止执行。
事件对象告诉您编辑了哪个范围。您可以获取该范围的工作表以了解编辑了哪个工作表。如果名称匹配,则执行其他内容。
function onEdit(e) {
if (e.range.getSheet().getName() === 'Items_Log') {
// Data validation
}
}
使用.getActiveRange()
或.getActiveSheet()
当您想要实际编辑的内容时,这不是很好的做法,因为编辑范围可能与函数执行时的活动范围不同,无论多么小。
推荐阅读
- r - Rstudio pdflatex.exe 没有成功
- rust - 生命周期参数和借用如何在函数签名中相互作用
- android - 为什么我的云函数返回最后一个返回值而不是之前的返回值?
- arrays - 对象作为 React 子对象无效(找到:带有键 {id, name} 的对象)。如果您打算渲染一组孩子,请改用数组
- html - 拉出占位符的一部分并放置在移动输入字段上方
- html - 如何“对齐”3 个响应式水平 DIV?
- angular - 在 Angular [Angular 10] 中为验证器使用全局变量
- angular - 如何销毁“动态 lightgallery”实例,以使其参考都不会出现在另一个角度组件上
- python - SHAP ValueError:两个形状中的维度 1 必须相等,但为 2 和 1。形状为 [?,2] 和 [?,1]
- oracle - 为什么我在创建触发器时不断收到此错误?