Ste*_*eve 2 replace for-loop range google-sheets google-apps-script
免责声明:我是Newb.我对脚本有点了解,但编写它对我来说很痛苦,主要是循环和数组,因此如下.
我试图从特定列中提取所有数据(在本例中为H [8]),检查该列中每个单元格的值,如果是ay,则将其更改为Yes; 如果是n,则将其更改为否; 如果它是空的,请不要管它并移动到下一个单元格.
这是我到目前为止所拥有的.像往常一样,我相信我非常接近,但我无法设置活动单元格的值,我无法看到我搞砸了它的位置.有一次,我实际上在列中将值改为Yes(所以感谢在这些情况下撤消).
工作表示例:
..... COL-H
r1... [service] <-- header
r2... y
r3... y
r4... n
r5... _ <-- empty
r6... y
Run Code Online (Sandbox Code Playgroud)
意图:将所有y改为是,将所有n改为否(跳过空白单元格).
到目前为止我尝试过的:
功能尝试1
function Thing1() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mySheet");
var lrow = ss.getLastRow();
var rng = ss.getRange(2, 8, lrow - 1, 1);
var data = rng.getValues();
for (var i=0; i < data.length; i++) {
if (data[i][0] == "y") {
data[i][0] == "Yes";
}
}
}
Run Code Online (Sandbox Code Playgroud)
功能尝试2
function Thing2() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mySheet");
var lrow = ss.getLastRow();
var rng = ss.getRange(2, 8, lrow - 1, 1);
var data = rng.getValues();
for (var i=0; i < data.length; i++) {
if (data[i][0] == "n") {
data.setValue("No");
} else if (data[i][0] == "y") {
data.setValue("Yes");
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
一旦我在这里完成,我想修改函数,以便我可以定位任何列并将一个值更改为另一个(我已经有了一个方法,但我需要能够设置值).它会是这样的:= replace(sheet,col,orig_value,new_value).我将在下面发布它.
在此先感谢您的帮助.
已完成的代码,用于在列中搜索和替换
function replace(sheet, col, origV1, newV1, origV2, newV2) {
// What is the name of the sheet and numeric value of the column you want to search?
var sheet = Browser.inputBox('Enter the target sheet name:');
var col = Browser.inputBox('Enter the numeric value of the column you\'re searching thru');
// Add old and new targets to change (Instance 1):
var origV1 = Browser.inputBox('[Instance 1:] What old value do you want to replace?');
var newV1 = Browser.inputBox('[Instance 1:] What new value is replacing the old?');
// Optional - Add old and new targets to change (Instance 2):
var origV2 = Browser.inputBox('[Instance 2:] What old value do you want to replace?');
var newV2 = Browser.inputBox('[Instance 2:] What new value is replacing the old?');
// Code to search and replace data within the column
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
var lrow = ss.getLastRow();
var rng = ss.getRange(2, col, lrow - 1, 1);
var data = rng.getValues();
for (var i=0; i < data.length; i++) {
if (data[i][0] == origV1) {
data[i][0] = newV1;
} else if (data[i][0] == origV2) {
data[i][0] = newV2;
}
}
rng.setValues(data);
}
Run Code Online (Sandbox Code Playgroud)
希望这有助于那里的人.再次感谢@ScampMichael!
名为data的数组是从范围中的值创建的,并且在创建后独立于电子表格,因此更改数组中的元素不会影响电子表格.您必须修改数组,然后将整个数组放回原来的位置.
for (var i=0; i < data.length; i++) {
if (data[i][0] == "n") {
data[i][0] = "No";
} else if (data[i][0] == "y") {
data[i][0] = "Yes";
}
}
rng.setValues(data); // replace old data with new
}
Run Code Online (Sandbox Code Playgroud)