此脚本似乎运行正常。这个问题更针对(初学者)如何写。
我一直在研究脚本,将其分解成多个函数之后,我很难将变量从第一个函数传递到下一个函数。阅读后,我发现我不一定需要包含“ var =”,尽管我不确定是否有100%的区别。我设法获得了“变量”(它们仍然被认为是变量吗?)传递给以下函数,但我只是想确保自己所做的事情是有效/可以接受的。
function onEdit(e){
/* I switched these from "var = " because they weren't passing
down to the following functions.
*/
activess = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeCell = activess.getActiveCell();
valueToFind = activeCell.getValue();
// Column Values
foundItemValues = [];
foundSubItemValues = [];
foundCatValues = [];
foundSubCatValues = [];
// These never change regardless of active sheet
catss = SpreadsheetApp.getActive().getSheetByName('Categories-Concat');
catData = catss.getRange(1,2,catss.getLastRow(),catss.getLastColumn()).getValues();
catIndex = catData[0].indexOf(activeCell.getValue()) + 2;
subCatIndex = catData[0].indexOf(activeCell.getValue()) + 2;
itemss = SpreadsheetApp.getActive().getSheetByName('Items');
itemdata = itemss.getRange(2,1,itemss.getLastRow(),4).getValues();
if(e.range.getSheet().getName() == 'projectSelections'){
activess = e.range.getSheet().getName();
colCss = SpreadsheetApp.getActive().getSheetByName('Categories-Concat');
colCdata = colCss.getRange(1,2,1,colCss.getLastColumn()).getValues();
colCIndex = colCdata[0].indexOf(activeCell.getValue()) + 2;
if(activeCell.getColumn() == 2 && activeCell.getRow() > 1){
this.subCategoryDV(e);
}
}
}
function subCategoryDV(e){
// Populate SUB-CATEGORY data validations
activeCell.offset(0, 1).clearDataValidations();
for (var q = 1; q < catData.length; q++){
for(var i=0;i<catData.length;i++){
if(valueToFind==catData[0][i]){
foundSubCatValues.push(catData[q][i]);
}
}
}
var subCatValidationRange = foundSubCatValues;
var subCatValidationRule = SpreadsheetApp.newDataValidation().requireValueInList(subCatValidationRange).build();
if(activeCell.getValue() != ""){
activeCell.offset(0, 1).setDataValidation(subCatValidationRule);
}
}
答案 0 :(得分:3)
关键字var
确保变量保留在局部范围内(大致上,只有变量所在的函数才能看到它。)请参见:What is the purpose of the var keyword and when should I use it (or omit it)?
通常,尝试将内容保持在本地状态是一个好习惯-全局变量存在很多问题,并且可以通过Google快速搜索为什么全局变量或邪恶(或类似的东西)会告诉您所有相关信息。
如果您尝试使用第二个函数,则需要同时传递引用的每个变量-activeCell
,catData
,valueToFind
和foundSubCatValues
'e'。
您可以做的另一件事是在函数subCategoryDV
中定义函数onEdit
。