Answers:
以下代码将向电子表格添加一个菜单:
侦探>跟踪相关者
选择此项将为带有所有相关单元格引用的活动单元格添加注释。
(添加了下面的Graham建议的对静态引用的搜索)
您可以在traceDependents函数中添加类似的函数,以在活动单元格中搜索“公式中搜索”函数中的文本。我将其留给您练习。
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = []
menuEntries.push({name: "Trace Dependents", functionName: "traceDependents"});
ss.addMenu("Detective", menuEntries);
}
function traceDependents(){
var dependents = []
var ss = SpreadsheetApp.getActiveSpreadsheet();
var currentCell = ss.getActiveCell();
var currentCellRef = currentCell.getA1Notation();
var range = ss.getDataRange();
var regex = new RegExp("\\b" + currentCellRef + "\\b");
var formulas = range.getFormulas();
for (var i = 0; i < formulas.length; i++){
var row = formulas[i];
for (var j = 0; j < row.length; j++){
var cellFormula = row[j].replace(/\$/g, "");
if (regex.test(cellFormula)){
dependents.push([i,j]);
}
}
}
var dependentRefs = [];
for (var k = 0; k < dependents.length; k ++){
var rowNum = dependents[k][0] + 1;
var colNum = dependents[k][1] + 1;
var cell = range.getCell(rowNum, colNum);
var cellRef = cell.getA1Notation();
dependentRefs.push(cellRef);
}
var output = "Dependents: ";
if(dependentRefs.length > 0){
output += dependentRefs.join(", ");
} else {
output += " None";
}
currentCell.setNote(output);
}
menuEntries.push({name: "Trace Dependents", functionName: "traceDependents"});
代码中出现两次?
这非常好,为我节省了很多工作-谢谢。
但是,以上答案找不到使用row-fixer或column-fixer的任何引用$
。
对代码进行以下微小更改即可完成此任务:
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = []
menuEntries.push({name: "Trace Dependents", functionName: "traceDependents"});
ss.addMenu("Detective", menuEntries);
}
function traceDependents(){
var dependents = []
var ss = SpreadsheetApp.getActiveSpreadsheet();
var currentCell = ss.getActiveCell();
var currentCellRef = currentCell.getA1Notation();
var range = ss.getDataRange();
var regex = new RegExp("\\b" + currentCellRef + "\\b");
var formulas = range.getFormulas();
for (var i = 0; i < formulas.length; i++){
var row = formulas[i];
for (var j = 0; j < row.length; j++){
var cellFormula = row[j].replace(/\$/g, "");
if (regex.test(cellFormula)){
dependents.push([i,j]);
}
}
}
var dependentRefs = [];
for (var k = 0; k < dependents.length; k ++){
var rowNum = dependents[k][0] + 1;
var colNum = dependents[k][1] + 1;
var cell = range.getCell(rowNum, colNum);
var cellRef = cell.getA1Notation();
dependentRefs.push(cellRef);
}
var output = "Dependents: ";
if(dependentRefs.length > 0){
output += dependentRefs.join(", ");
} else {
output += " None";
}
currentCell.setNote(output);
}