use*_*263 3 javascript loops google-sheets google-apps-script
我试图遍历我的谷歌工作表中的整行,并将一些数据从一张工作表复制到另一张工作表。随着时间的推移,列表会变得更长。
更具体地说:如果 B 列中的输入等于“蓝色”,则将 A 列和 C 列中的值复制到另一个工作表中。对所有列执行此操作,直到列末尾。
链接到我的电子表格:https : //docs.google.com/spreadsheets/d/1xnLygpuJnpDfnF6LdR41gN74gWy8mxhVnQJ7i3hv1NA/edit?usp=sharing
非常感谢任何评论、提示或帮助。
问候!
你有两个选择。第一种是使用 Google Sheets 中的标准 query() 函数来获取值。这里的缺点是它只是值的参考。因此您不能对它们重新排序等。要使用它,请将其放置在单元格 A1 中,它将拉出标题并从 A 列和 C 列中检索值:
=QUERY(A:C, "select A, C where B = 'blue'", 1)
Run Code Online (Sandbox Code Playgroud)
对于 Google Apps 脚本答案:这将循环遍历您的列表工作表,并且对于 B 列为蓝色的每一行,它会将 A 列和 C 列中的值保存到新工作表的 A 列和 B 列:
function doIt(){
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet4");
var lastRow = activeSheet.getLastRow();
var lastCol = activeSheet.getLastColumn();
var targetValues = [];
var sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("List");
var lastSourceRow = sourceSheet.getLastRow();
var lastSourceCol = sourceSheet.getLastColumn();
var sourceRange = sourceSheet.getRange(1, 1, lastSourceRow, lastSourceCol);
var sourceData = sourceRange.getValues();
var activeRow = 0;
//Loop through every retrieved row from the Source
for (row in sourceData) {
//IF Column B in this row has 'blue', then work on it.
if (sourceData[row][1] === 'blue') {
//Save it ta a temporary variable
var tempvalue = [sourceData[row][0], sourceData[row][2]];
//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
activeSheet.getRange(lastRow + 1, 1 , targetValues.length, 2).setValues(targetValues);
}
Run Code Online (Sandbox Code Playgroud)
当然,您可以通过替换 2 行来将要测试的值传递给函数。首先,定义函数:
function doIt(testingvar){
Run Code Online (Sandbox Code Playgroud)
传递一个名为testingvar的变量,以及用传递的变量替换硬编码测试的测试行:
if (sourceData[row][1] === testingvar) {
Run Code Online (Sandbox Code Playgroud)
你有一个名为“List”的输入表,我将输出表命名为“Output”。这是代码。
function condCopy()
{
var s = SpreadsheetApp.getActiveSpreadsheet();
var sht = s.getSheetByName('List')
var drng = sht.getDataRange();
var rng = sht.getRange(2,1, drng.getLastRow()-1,drng.getLastColumn());
var rngA = rng.getValues();//Array of input values
var rngB = [];//Array where values that past the condition will go
var b = 0;//Output iterator
for(var i = 0; i < rngA.length; i++)
{
if(rngA[i][1] == 'blue')
{
rngB[b]=[];//Initial new array
rngB[b].push(rngA[i][0],rngA[i][2]);
b++;
}
}
var shtout = s.getSheetByName('Output');
var outrng = shtout.getRange(2,1,rngB.length,2);//Make the output range the same size as the output array
outrng.setValues(rngB);
}
Run Code Online (Sandbox Code Playgroud)