使用Google App脚本我希望找到Sheet1中存在的任何ID,并将Sheet1中的注释字段附加到Sheet2的“注释”字段中列出的内容。
Sheet1:根据ID
保存所有数据Sheet2:保存有关Sheet1中某些ID的注释
Sheet1示例
ID Type In Stock Comment
1 Apple Yes
2 Banana No
3 Orange Yes
Sheet2示例
ID Comment
1 Text
2 Text
代码
这是我一直用于其他东西的代码,它循环我的源数据以识别一个名为“是”的变量,显然这不适用于这种情况,因为ID是我们需要找到的变量,这是动态。
我对如何修改此代码有点迷失,因此它将遍历Sheet2,获取所有ID,检查这些ID对Sheet1。如果Sheet1中存在这些ID,则使用Sheet2中已列出的注释更新Sheet1的注释
function setComment(){
var outputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var lastRow = outputSheet.getLastRow();
var lastCol = outputSheet.getLastColumn();
var targetValues = [];
var sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var lastSourceRow = sourceSheet.getLastRow();
var lastSourceCol = sourceSheet.getLastColumn();
var sourceRange = sourceSheet.getRange(1, 1, lastSourceRow, lastSourceCol);
var sourceData = sourceRange.getValues();
{
//Loop through every retrieved row from the Source
for (row in sourceData) {
//IF Column I in this row has 'Yes', then work on it.
if (sourceData[row][1] === 'Yes') {
//Save it ta a temporary variable
var tempvalue = [sourceData[row][0], sourceData[row][7]];
//then push that into the variables which holds all the new values to be returned
targetValues.push(tempvalue);
}
}
//Save the new range to the appropriate sheet starting at the last empty row
outputSheet.getRange(lastRow + 1, 1 , targetValues.length, 2).setValues(targetValues);
}
}
答案 0 :(得分:2)
是的,您需要遍历一组ID。在该循环中,您需要嵌套一个遍历另一组ID的循环。
<强>代码强>
function setComments() {
var ss = SpreadsheetApp.getActive(),
compare1 = "", compare2 = "",
outputSheet = ss.getSheetByName("Sheet1"),
sourceSheet = ss.getSheetByName("Sheet2"),
range1 = outputSheet.getDataRange(),
range2 = sourceSheet.getDataRange(),
lastCol1 = range1.getNumColumns(),
lastCol2 = range2.getNumColumns(),
values1 = range1.getValues(),
values2 = range2.getValues(),
// get the range of the titles
titleSection1 = outputSheet.getRange(1,1,1, lastCol1),
titleSection2 = sourceSheet.getRange(1,1,1, lastCol2),
// get the values from the titles
titles1 = titleSection1.getValues(),
titles2 = titleSection2.getValues(),
// get the column # for "ID" and "comment"
idCol1 = titles1[0].indexOf("ID"),
idCol2 = titles2[0].indexOf("ID"),
commentsCol1 = titles1[0].indexOf("comment"),
commentsCol2 = titles2[0].indexOf("comment");
// get the IDs from range1
for (i = 1; i < values1.length; i++) {
compare1 = values1[i][idCol1];
// get the IDs from range2
for (j = 1; j< values2.length; j++){
compare2 = values2[j][idCol2];
// if same ID, change the values array
if (compare1 == compare2) {
values1[i][commentsCol1] = values2[j][commentsCol2];
}
}
}
// set values based on the values array
range1.setValues(values1);
}