UPDATE -- this is a complete rewrite of the question on Monday 11/26
This code works:
name_this_table = "station_list"+i;
station_table = document.getElementById(name_this_table);
for (station_index in station_detail)
{
newRow = station_table.getElementsByTagName("tbody")[0].insertRow(-1);
newCell = newRow.insertCell(-1);
newCell.appendChild(document.createTextNode("one"));
newCell = newRow.insertCell(-1);
newCell.appendChild(document.createTextNode("two"));
newRow = null;
}
But I want to use createDocumentFragment(), like this:
name_this_table = "station_list"+i;
station_table = document.getElementById(name_this_table); // NOTE 1
//station_table = document.getElementById(name_this_table).tBodies[0];
var tableFrag;
tableFrag = document.createDocumentFragment();
tableFrag.appendChild(station_table); // NOTE 2
for (station_index in station_detail)
{
newRow = station_table.getElementsByTagName("tbody")[0].insertRow(-1); // NOTE 3
//newRow = tableFrag.getElementsByTagName("tbody")[0].insertRow(-1);
newCell = newRow.insertCell(-1);
newCell.appendChild(document.createTextNode("one"));
newCell = newRow.insertCell(-1);
newCell.appendChild(document.createTextNode("two"));
newRow = null;
}
document.getElementById(name_this_table).appendChild(tableFrag);
I have various failures to report -- not run-time errors, but the rendering stops.
NOTE 1 (above) -- I have tried the line below (uses tbodies) as an
alternative.
NOTE 2 -- If I uncomment this line, the rendering stops
at that point.
NOTE 3 -- Here I am trying to use the tableFrag ...
NEW ANSWER posted Tuesday 11/27
After a lot of experimenting, this works. I'd love any feedback (for one thing, I'm not sure I'm seeing a performance gain.
name_this_table = "station_list"+i;
station_table = document.getElementById(name_this_table);
var tableFrag;
tableFrag = document.createDocumentFragment();
tableFrag.appendChild(station_table); // NOTE 2
for (station_index in station_detail)
{
station_id = station_detail[station_index]["station_id"];
var newRow;
newRow = document.createDocumentFragment();
newRow = station_table.getElementsByTagName("tbody")[0].insertRow(-1);
newCell = newRow.insertCell(-1);
newCell.appendChild(document.createTextNode("one"));
...
station_table.appendChild(newRow);
newRow = null;
}
Related
Our company offers soft loans to employees. I am trying to write some code that will set up a loan deduction schedule once a loan is approved. This is all done on google sheets. The schedule then can be linked to payroll etc.
The approved loans will appear in a format like this:-
Loans Approved - [Serial, Employee ID,Amount, Monthly Deductions,Requested Date,Deduction Start Date]
I am looking to build an array that will have the first 4 elements that repeat and the deduction month to increase by 1
So far this is my code
function myFunction() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Loans");
var range = sheet.getDataRange();
var data = range.getValues()
var lastRow = range.getLastRow()
var scheduleSheet = ss.getSheetByName("Schedule")
var scheuduleLastRow = scheduleSheet.getDataRange().getLastRow;
for(let i=1;i<lastRow;i++){
var serial = data [i][0]
var id = data [i][1]
var amount = data[i][2]
var monthlyRepayment = data [i][3]
var startDate = new Date (data [i][5])
var markScheduleDone = sheet.getRange(i+1,7)
var fullMonths = Math.floor(amount/monthlyRepayment)
var remainderMonth = (amount/monthlyRepayment)-fullMonths
var remainderAmount = Math.round(remainderMonth*monthlyRepayment)
for (let j=1;j<=fullMonths+1;j++){
var incrementalMonths = new Date(startDate.setMonth(startDate.getMonth()+1)) ;
}
var newArray = [serial,id,monthlyRepayment];
var remainderArray = [serial,id,remainderAmount];
var reptArray = Array(fullMonths).fill(newArray);
var finalArray = [...reptArray,remainderArray]
Logger.log(finalArray)
var toPasteto = scheduleSheet.getRange(scheuduleLastRow+1,1,finalArray.length,3)
toPasteto.setValues(finalArray)
markScheduleDone.setValue ("Done")
}
}
I am close but I cant figure out how to join the incrementalMonths to the finalarray.
This is the first time im using a loop within a loop
Also any guidance if I could have done this better?
Kinldy requesting some guidance
I'm not sure if this is exactly what you are looking for but try this.
Notice I fill the array finalArray with all the newArrays so I only have to setValues() once. Same with markDone.
I increment the month but if the day happens to fall outside the number of days in a month it will increment to another day. So for any 28 or 30 day months there should be another check but I didn't do that.
My particular style of coding is to always use a try {} catch() {} block, always terminate a line with semicolon ;, and to use let instead of var whenever possible.
function myFunction() {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Loans");
var range = sheet.getDataRange();
var data = range.getValues()
var lastRow = range.getLastRow()
var scheduleSheet = ss.getSheetByName("Schedule")
var scheuduleLastRow = scheduleSheet.getDataRange().getLastRow();
let finalArray = [];
let markDone = [];
for(let i=1;i<lastRow;i++){
var serial = data [i][0];
var id = data [i][1];
var amount = data[i][2];
var monthlyRepayment = data [i][3];
var startDate = new Date (data [i][5]);
var fullMonths = Math.floor(amount/monthlyRepayment);
var remainderMonth = (amount/monthlyRepayment)-fullMonths;
var remainderAmount = Math.round(remainderMonth*monthlyRepayment);
let day = startDate.getDate();
if( day > 28 ) throw "This function has not adjusted for short months"
let month = startDate.getMonth();
let year = startDate.getFullYear();
let newArray = [];
for (let j=1;j<=fullMonths+1;j++){
month++;
if( month > 11 ) {
month = 0;
year++;
}
var date = new Date(year,month,day);
newArray.push([serial,id,monthlyRepayment,date])
}
newArray.push([serial,id,remainderAmount,date]);
finalArray = finalArray.concat(newArray);
Logger.log(newArray);
markDone.push(["Done"]);
}
sheet.getRange(2,7,markDone.length,1).setValues(markDone);
scheduleSheet.getRange(scheuduleLastRow+1,1,finalArray.length,4).setValues(finalArray);
}
catch(err) {
Logger.log(err)
}
}
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.
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)
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.
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
}