如何根据所选单元格的值在电子表格单元格上创建注释



为了让这个特定的功能工作,我在一个简单的测试表中尝试了一下。

我在FEBRUARI工作表中有两张(状态和FEBRUARI(,我选择了某个单元格。此单元格具有值。我希望脚本做的是查看该值,在 STATUS 工作表中找到该值(假设它在 A1 中找到它(,然后将 B1 中的值返回到 FEBRUARI 工作表中所选单元格中的单元格注释。例如:在单元格中它说"项目 6",单元格注释提供有关该项目的信息。

这就是我得到的。这给了我一定的值(-1(,但我把查找值放在哪里似乎并不重要。它始终返回 -1。

// My Script
function noteSetter() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lookupvalue = SpreadsheetApp.getActiveSheet().getActiveCell().getValue();
var sheet = ss.getSheetByName("STATUS"); //source sheet
var sheet2 = ss.getSheetByName("FEBRUARI"); //result sheet
var cellnote = SpreadsheetApp.getActiveSheet().getActiveCell();
var lc = sheet.getLastColumn()
var lookup = sheet.getRange(1,1,1,lc).getValues() //
var index = lookup.indexOf(lookupvalue)

cellnote.setNote(index);

// This part will actually run the script once it's up and running
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Set cell note",
functionName : "noteSetter"
}];
sheet.addMenu("Scripts", entries);
};

}
var lookup = sheet.getRange(1,1,1,lc).getValues();
var index = lookup.indexOf(lookupvalue)

第一行返回一个 2D 数组。 indexOf(( 仅适用于扁平数组。 尝试使用:

var lookup = sheet.getRange(1,1,1,lc).getValues()[0];

根据谷歌的说法,最好使用getCurrentCell()而不是getActiveCell(),因为它返回当前突出显示(或选定的(单元格。

此外,您的onOpen()函数应位于noteSetter()函数之外,否则电子表格打开时不会调用它。

以下代码将为像您这样的工作表执行您想要的操作。如果更改了数据顺序,则必须相应地更改范围公式。

/* 
* This function will run when the Spreadsheet is opened and,
* will add a Menu item for the noteSetter function 
*/
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Set cell note",
functionName : "noteSetter"
}];
sheet.addMenu("My Menu", entries);
};
function noteSetter() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("STATUS"); //source sheet
var sheet2 = ss.getSheetByName("FEBRUARI"); //result sheet
var noteCell = sheet2.getCurrentCell();
var lookUpValue = noteCell.getValue();
// Search through Col C in "STATUS" sheet to get the matching row
// You need to transpose the lookUpRange 
var lookUpRange = sheet.getRange(2,3,sheet.getDataRange().getLastRow(),1).getValues();
lookUpRange = transpose(lookUpRange);
var index = lookUpRange[0].indexOf(lookUpValue);  // Starts at 0
var row = index + 2;  // One for the omitted header and one because rows start at 1
var note = sheet.getRange(row,7).getValue();
noteCell.setNote(note);
}
// You need to transpose to avoid looping through the array
function transpose(a)
{
return Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });
}

最新更新