首页 > 解决方案 > 试图将现有脚本限制为特定工作表

问题描述

我的第一个问题是,我有一个项目日志表,我想在其中添加和管理我们库存中的单个独特项目。我为主要类别创建了一个数据验证相关下拉列表,并了解了如何构建脚本以根据所选主要类别动态创建次要类别下拉列表。

例如:如果单元格 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)
}
}

此外,无论有多少行,有没有办法运行清晰的验证?

标签: google-apps-scriptgoogle-sheets

解决方案


只要有编辑,该功能就会运行,您无法阻止它。相反,如果它不是您关心的工作表,您可以先发制人地终止执行。

事件对象告诉您编辑了哪个范围。您可以获取该范围的工作以了解编辑了哪个工作表。如果名称匹配,则执行其他内容。

function onEdit(e) {
  if (e.range.getSheet().getName() === 'Items_Log') {
    // Data validation
  }
}

使用.getActiveRange().getActiveSheet()当您想要实际编辑的内容时,这不是很好的做法,因为编辑范围可能与函数执行时的活动范围不同,无论多么小。


推荐阅读