How to repeat the values until next non-empty row and then repeat next row's data and so on with Google Apps Script? - for-loop

The challenge here is to capture the customer ID and its name and repeat it down below until the script reaches the next non-empty row. Then, the next ID and customer name are the ones that will be repeated.
This is just how far I've gotten on my own, but I can't build the core of the logic mylself (yes).
function repeatValues() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("Sheet1");
const originData = sheet.getRange(6, 1, sheet.getLastRow(), 3).getValues();
const targetSheet = ss.getSheetByName("Sheet2");
for (var a = 0; a < originData.length; a++) {
if (originData[a][0] != ''){
var customerID = originData[a][0];
var customer = originData[a][1];
}
if (originData == ''){
targetSheet.getRange(2,1,originData.length, originData.length).setValue(customerID);
}
}
}
Here's a link to the sample spreadsheet: https://docs.google.com/spreadsheets/d/1wU3dql6dnh_JBC6yMkrFzEYxdyzyNdkBmve2pfyxG0g/edit?usp=sharing
Expected Result includes these values in blue repeated:
Any help is appreciated!

I believe your goal as follows.
You want to achieve the following situation. (The following image is from your question.) You want to add the texts of blue font color.
You want to put the values to "Sheet2".
Modification points:
In your script, at const originData = sheet.getRange(6, 1, sheet.getLastRow(), 3).getValues();, the start row is 6. In this case, please modify sheet.getLastRow() to sheet.getLastRow() - 5
In order to create an array for putting to "Sheet2", it is required to check the columns "A" and "B" of "Sheet1". For this, in this modification, I used temp as follows.
When above points are reflected to your script, it becomes as follows.
Modified script:
function repeatValues() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("Sheet1");
const originData = sheet.getRange(6, 1, sheet.getLastRow() - 5, 3).getValues(); // Modified
const targetSheet = ss.getSheetByName("Sheet2");
// I added below script.
let temp = ["", ""];
const putValues = originData.map(([a, b, c]) => {
if (a.toString() && b.toString() && temp[0] != a && temp[1] != b) {
temp = [a, b];
}
return temp.concat(c);
});
targetSheet.getRange(2, 1, putValues.length, putValues[0].length).setValues(putValues);
}
Note:
This modified script is for your sample Spreadsheet. So when the structure of Spreadsheet is changed, the script might not be able to be used. Please be careful this.
Reference:
map()

Related

Google Script - Macro to get data from a TABLE A and paste required values to Table B in sequence using LOOP

I seek help in finalizing a MACRO script for following task.
Basic requirements is to get data from 'Ref' tab (around 200 symbols) in a sequence to 'Mcontrol'!E3 (this tab imports a table from the Website)
From this table, sorted highest 2 values of Symbol/s is extracted and exported to 'OI EOD' tab,
i.e. required value is shown in 'OI EOD'! G5:K5.
Then, copy paste range 'OI EOD'! G5:K5 , to the matched row (symbol match to 'Mcontrol'!E3) in the table below ('OI EOD'!C6:C210).
I seek help in putting forEach condition in the macro. SO that next cycle of copy paste function is completed, for each new value in Cell_1 reference.
Hope ppl take notice of the help request from a novice and give good solution and guidance.
Sheet link is Following
https://docs.google.com/spreadsheets/d/1az2kas91KFxHcWhtWDg-g20hNYR-_zEiWPvYs-x42YU/edit?usp=sharing
Macro -
var wb = SpreadsheetApp.getActive();
var sh1= wb.getSheetByName('Mcontrol');
var sh2= wb.getSheetByName('OI EOD');
var R1 = 3
var C1 = 3
var R2 = 3
var C2 = 2
var R3 = 3
var C3 = 5
var cell_1 = sh1.getRange(R1,C1).getValue();
var cell_2 = sh1.getRange(R2,C2).getValue();
var cell_3 = sh1.getRange(R3,C3).getValue();
for(i=1;i<cell_2;i++);
cell_1 = i + 1;
sh1.getRange(R1,C1).setValue(cell_1);{
var Range_1 = sh2.getRange(6, 3, 300);
var row_i = 5 ; // source row no. for data copy paste
const Row_1 = row_i;
const Col_2 = 7;
const Row_Offet1 = 1;
const Col_Offet1 = 5;
var data = Range_1.getValues();
let ABC = cell_3;
let row = 1 + data.findIndex(users => {return users[0] == ABC});
var row_target = row + row_i ;
const sourceRange = sh2.getRange(Row_1,Col_2,Row_Offet1,Col_Offet1);
var destRange = sh2.getRange(row_target,Col_2,Row_Offet1,Col_Offet1);
sourceRange.copyTo(destRange,SpreadsheetApp.CopyPasteType.PASTE_VALUES,false);
for(k=1;k<cell_1.i;k++);
Logger.log(row_target);
Logger.log(k) ;
}
//NEXT
// cell_1=sh1.getRange(R1, C1);
// sh1.getRange(R1,C1).setValue(i);
}
}```
Thanks
Robin
Not sure if understand the task as a whole, so here is a guess.
This way you can get values from some start to some end 'symbols' (or numbers) and put these values in correct rows on the 'OI EOD' sheet:
function main() {
var start = 1;
var end = 5;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mcontrol_sheet = ss.getSheetByName('Mcontrol');
var oi_eod_sheet = ss.getSheetByName('OI EOD');
// get a list of all Symbols from column 'C' of the sheet 'OI EOD'
var symbols = oi_eod_sheet.getRange('c6:c').getValues().flat();
for (let i = start; i <= end; i++) {
// set the number i on the sheet 'Mcontrol' into the cell 'C3'
mcontrol_sheet.getRange('c3').setValue(i);
// wait to complete all the changes on the spreadsheet
SpreadsheetApp.flush();
// get the Symbol and Values from the range 'C5:K5' of the sheet 'OI EOD'
var [symbl, _, _, _, ...values] = oi_eod_sheet.getRange('c5:k5').getValues()[0];
// get the row index for this Symbol on the sheet 'Mcontrol'
var row = symbols.indexOf(symbl) + 6;
console.log({row}, {symbl}, {values});
// set the values on the sheet 'OI EOD' on the row with given index
oi_eod_sheet.getRange('g' + row + ':k' + row).setValues([values]);
}
}
It's up to you to decide how the start and end values could be defined. It can be values from two cells. Or it can be selected range. Or something else.

Why does the looping in Google Sheet App Script stop in middle of the looping process and the rest of the codes do not run?

I tried the "for loop" and "do ... while ...", both of them stopped in the middle of the looping process, and the rest of the codes, which come after the loop, did not run. This becomes an issue when I loop through hundreds of rows.
I know that the use of array is a better solution as the code execution is faster, but I have a difficulty in setting the borders in batch as there is no ".setBorders(Array)" function in Google Sheets.
The sheet provided here has been simplified only to show the looping issues. The actual sheet is written to automatically create hundreds of tables with different values, font weights and horizontal alignments.
What I want to do:
Choose the option "Yes" to start the looping (the current row of looping is also tracked and recorded in "CURRENT ROW" and the "STATUS" shows "Processing ...")
The program will check the "SCORE" column, if "SCORE" is empty (""), than the font weight for that row is set to "bold", else, the font weight is set to "normal"
If the looping is done until the last row, the "STATUS" shows "Done".
The following is the copy of the Google App Script:
let app = SpreadsheetApp;
let ss = app.getActiveSpreadsheet();
let activeSheet = ss.getActiveSheet();
let sheetName = activeSheet.getName();
let sheet1 = ss.getSheetByName("Sheet1");
let loopOptionRange = sheet1.getRange(4, 4);
let loopOption = loopOptionRange.getValue();
let loopStatusRange = sheet1.getRange(4, 7);
function onEdit(e) {
}
function onOpen() {
loopOptionRange.setValue("Choose");
sheet1.getRange(4, 5).setValue(5);
loopStatusRange.setValue("");
}
function loopTest() {
const startRow = 4; //table head
const lastRow = sheet1.getLastRow();
sheet1.getRange(4, 6).setValue(lastRow);
const startRowLoop = startRow + 1; //first row of looping
try {
for (i = startRowLoop; i <= lastRow; i++) {
const testStatus = sheet1.getRange(i, 3).getValue();
sheet1.getRange(4, 5).setValue(i);
if (testStatus == "") {
sheet1.getRange(i, 1, 1, 2).setFontWeight("bold");
} else {
sheet1.getRange(i, 1, 1, 3).setFontWeight("normal");
}
}
loopStatusRange.setValue("Done");
loopOptionRange.setValue("Choose");
} catch (error) {
app.getUi().alert(`An error occured.`);
}
}
if (sheetName === "Sheet1"){
if (loopOption == "Yes") {
loopStatusRange.setValue("Processing ...");
loopTest();
} else if (loopOption === "Cancel") {
loopOptionRange.setValue("Choose");
}
}
LOOP TEST - Google Sheets file
When I saw your script, getValue, setValue and setFontWeight are used in a loop. In this case, the process cost will become high. I thought that this might be the reason for your issue. In order to reduce the process cost of your script, how about the following modification?
From:
for (i = startRowLoop; i <= lastRow; i++) {
const testStatus = sheet1.getRange(i, 3).getValue();
sheet1.getRange(4, 5).setValue(i);
if (testStatus == "") {
sheet1.getRange(i, 1, 1, 2).setFontWeight("bold");
} else {
sheet1.getRange(i, 1, 1, 3).setFontWeight("normal");
}
}
To:
const range = sheet1.getRange(startRow, 3, lastRow - startRowLoop);
const values = range.getDisplayValues().map(([c]) => [c ? null : "bold"]);
range.offset(0, -1).setFontWeights(values);
Note:
About Is it really because of "the high process cost" you mentioned in your answer?, when I saw your script for the 1st time, I thought that the reason for your issue might be due to the process cost. Because, when the script is run by OnEdit trigger, the maximum execution time is 30 seconds. And, when I tested your script and your Spreadsheet, when I saw the log after the script was stopped, an error related to the over of the maximum execution time. By this, I resulted that the reason for your issue is due to the process cost of the script.
References:
map()
setFontWeights(fontWeights)

Add a status to each proccesed row in for loop that has an if statement with Google App Script

I've got a for loop in App script that is looking only at rows that have data in two columns. I'd like to set a status on each row that is actually processed, but the statuses get added to the wrong rows. When I add to i it adds to the whole length of the array, so I guess I shouldn't be trying to process each row, what am I doing wrong?
function auditReport() {
var sheetname = "Sheet1"; // name of data sheet ex. Form Responses 1
var colstoworkon = 10; // how many cols are filled with data f.e. by a form
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName(sheetname));
var sheet = ss.getSheetByName(sheetname);
var data = sheet.getRange(3,1,sheet.getLastRow()-1,colstoworkon).getValues(); // starting with row 2 and column 1 as our upper-left most column,
//This makes it loops continuously and checks all not done rows
for (var i in data) {
if(data[i][1] && data[i][2]){//if email or copy are undefined just skip
var setStatus = sheet.getRange(i,4).setValue("done")
} // end of if
} // End of Loop
} //End of email function
Modification points:
In your script, from getRange(3,1,sheet.getLastRow()-1,colstoworkon), in this case, it is required to be getRange(3,1,sheet.getLastRow()-2,colstoworkon).
In the case of for (var i in data) {, i is the string type.
When you want to use sheet.getRange(i,4).setValue("done"), it is required to be sheet.getRange(Number(i) + 3, 4).setValue("done").
I thought that this might be the reason of your issue of but the statuses get added to the wrong rows..
In the case of if (data[i][1] && data[i][2]) {, if the value is 0, data[i][1] && data[i][2] is false.
When these points are reflected to your script, it becomes as follows.
Modified script:
function auditReport() {
var sheetname = "Sheet1";
var colstoworkon = 10;
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName(sheetname));
var sheet = ss.getSheetByName(sheetname);
var data = sheet.getRange(3, 1, sheet.getLastRow() - 2, colstoworkon).getDisplayValues();
for (var i in data) {
if (data[i][1] && data[i][2]) {
var setStatus = sheet.getRange(Number(i) + 3, 4).setValue("done");
}
}
}
Or, your script can be also modified as follows. In this modification, done is put using the range list. By this, the process cost can be reduced a little.
function auditReport() {
var sheetname = "Sheet1";
var colstoworkon = 10;
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName(sheetname));
var sheet = ss.getSheetByName(sheetname);
var data = sheet.getRange(3, 1, sheet.getLastRow() - 2, colstoworkon).getDisplayValues();
var ranges = data.map(([,b,c], i) => b && c ? `D${i + 3}` : "").filter(String);
if (ranges.length == 0) return;
sheet.getRangeList(ranges).setValue("done");
}
References:
for...in
getRangeList(a1Notations)

Why is this getting the same row twice in second loop?

The code below runs with no apparent errors, but despite I've looked for all possible causes I could think of, I couldn't find the reason why it gets the correct row iterated, marks it as processed ("Sim), and from the 2º iteration on, it gets the new row, but repeats the others already iterated over.
function formToData() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var ss = sheet.getSheetByName("Form Responses 1");
var targetSheet = sheet.getSheetByName("Cadastro de Cliente");
var StartRow = 2;
var RowRange = ss.getLastRow() - StartRow + 1;
var WholeRange = ss.getRange(StartRow, 1, RowRange, 30);
var AllValues = WholeRange.getValues();
var message = "";
for (var i = 0; i < AllValues.length; i++) {
var currentRow = AllValues[i];
//if row has been sent, then continue to next iteration
if (currentRow[0] != "" && currentRow[29] != "Sim") {
//set the row to look at
var setRow = parseInt(i) + StartRow;
var data = currentRow[0];
var dataFormatted = Utilities.formatDate(data, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "dd/MM/yyyy', às 'HH:mm") + "hs";
//set HTML template for information
message +=
"<p><b>Data: </b>" + dataFormatted + "</p>" +
"<p><b>Unidade: </b>" + currentRow[1] + "</p>"
//mark row as "sent"
ss.getRange(setRow, 30).setValue("Sim");
var values = targetSheet.getRange("A:A").getValues();
var maxIndex = values.reduce(function (maxIndex, row, index) {
return row[0] === "" ? maxIndex : index;
}, 0);
targetSheet.getRange(maxIndex + 2, 1, 1, 30)
.setNumberFormat("#")
.setValues([currentRow]);
var sendTo = "email";
var subject = "Cadastro de cliente novo";
if (message) {
MailApp.sendEmail({
to: sendTo,
subject: subject,
name: "Comercial - Emape",
htmlBody: message,
});
}
}
}//For loop closes
}
I'd appreaciate if you could help me find the flaw.
I tried to replicate this behavior, however, on a static sheet the script performs as expected:
Set unmarked rows in column 30 as 'Sim'.
Copy these rows to a separate sheet starting from the first empty row (or whichever row that Column A is empty).
Given the names of the functions and the sheets, this may be a Sheet generated by a Google Form. These sheets are dynamic, and there is a possibility that the contents may change while your script is running, especially if users are allowed to edit responses.
As a workaround, I suggest to lock the form before running the script:
Also, check the contents of the sheet and form for any possibility that the "Sim" mark might be overwritten by new or edited form data, maybe the sheet is inserting 30 columns instead of 29 or less.

Replace certain cell values in a column

Disclaimer: I am Newb. I understand scripting a little, but writing it is a pain for me, mostly with loops and arrays, hence the following.
I am attempting to pull all of the data from a specific column (in this case H [8]), check each cell's value in that column and if it is a y, change it to Yes; if it's n, change it to No; if it's empty, leave it alone and move onto the next cell.
Here's what I have so far. As usual, I believe I'm pretty close, but I can't set the value of the active cell and I can't see where I'm messing it up. At one point I actually changed ever value to Yes in the column (so thankful for undo in these cases).
Example of Sheet:
..... COL-H
r1... [service] <-- header
r2... y
r3... y
r4... n
r5... _ <-- empty
r6... y
Intent: Change all y's to Yes and all n's to No (skip blank cells).
What I've tried so far:
Function attempt 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";
}
}
}
Function attempt 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");
}
}
}
Usage:
Once I'm done here, I want to modify the function so that I can target any column and change one value to another (I already have a method for that, but I need to be able to set the value). It would be like so: =replace(sheet, col, orig_value, new_value). I will post it as well below.
Thanks in advance for the help.
Completed Code for searching and replacing within a column
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);
}
Hope this helps someone out there. Thanks Again #ScampMichael!
The array named data was created from the values in the range and is independent of the spreadsheet after it is created so changing an element in the array does not affect the spreadsheet. You must modify the array and then put the whole array back where it came from.
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
}

Resources