my variable are grey and its say these variable are not present in the function
function regle() {
var spreadsheet = SpreadsheetApp.getActive();
var p = spreadsheet.getRange('A1').getValue();
var t = spreadsheet.getRange('C1').getValue();
if (t = 1) if (p = 1) {
spreadsheet.getRange('B1').activate();
spreadsheet.getActiveRange().setValue(1);
}
else if (t = 2) if (p = 2) {
spreadsheet.getRange('B1').activate();
spreadsheet.getActiveRange().setValue(2);
}
else if (t = 1) if (p = 2)
spreadsheet.getRange('B1').activate();
spreadsheet.getActiveRange().setValue(2);
};
Related
I'm trying to write a google script that will updates the sensor data google sheet.This part is ok.
And I try to add a function clearRange(), when the data updated to 100 rows and delete the first 100 rows and reupdate the data. Is there something that I'm missing here?
function doGet(e) {
Logger.log( JSON.stringify(e) );
var sheet_id = 'XXXXXXXXXXXXXXXXXXXXX'; // Spreadsheet ID
var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
var newRow = sheet.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else if(e.parameter != 'undefined'){
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "GMT+8", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'temperature':
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
break;
case 'humidity':
rowData[3] = value; // Humidity in column D
result += ' ,Humidity Written on column D';
break;
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
else if (newRow==100)
{
clearRange();
}
return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}
function clearRange() {
sheet.deleteRows(1,100);
}
Try this:
function doGet(e) {
var sheet_id = 'XXXXXXXXXXXXXXXXXXXXX'; // Spreadsheet ID
var sh = SpreadsheetApp.openById(sheet_id).getActiveSheet();
var newRow = sh.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else if (e.parameter != 'undefined') {
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "GMT+8", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
var value = e.parameter[param].replace(/['"]+/g, '');
switch (param) {
case 'temperature':
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
break;
case 'humidity':
rowData[3] = value; // Humidity in column D
result += ' ,Humidity Written on column D';
break;
default:
result = "unsupported parameter";
}
}
var newRange = sh.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
else if (newRow == 100) {
sh.deleteRows(1, 100);
}
return ContentService.createTextOutput(result);
}
This is the first question I have posted on Stack Overflow so I apologize if I am doing this wrong. I have a tracker for work where I am trying to hide rows with a script that meets 2 conditions. 1. If a row contains "rejected" or "withdrew" 2. Date older than the previous quarter (in this case 1/1/2022). I can get the script to hide rows with just the words no problem but I have no clue how to do the date because I think it is a different syntax.
The dates are in column K, M, O, Q, S, U, W.
Here is the code I am currently using:
function Hide() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
for (var sheetI = 1; sheetI <= 3; sheetI++) {
var sheet = sheets[sheetI];
sheet.showRows(1, sheet.getMaxRows());
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("Data Validation");
var v = s.getRange("A2").getValues();
var kk = SpreadsheetApp.getActiveSpreadsheet();
var k = kk.getSheetByName("SM");
var a = k.getRange("K:K").getValue();
var b = k.getRange("M:M").getValue();
var c = k.getRange("O:O").getValue();
var d = k.getRange("Q:Q").getValue();
var e = k.getRange("S:S").getValue();
var f = k.getRange("U:U").getValue();
var g = k.getRange("W:W").getValue();
var colJ = sheet.getRange("J:J").getValues().map(function(row) {return row[0];});
var colL = sheet.getRange("L:L").getValues().map(function(row) {return row[0];});
var colN = sheet.getRange("N:N").getValues().map(function(row) {return row[0];});
var colP = sheet.getRange("P:P").getValues().map(function(row) {return row[0];});
var colR = sheet.getRange("R:R").getValues().map(function(row) {return row[0];});
var colT = sheet.getRange("T:T").getValues().map(function(row) {return row[0];});
var colV = sheet.getRange("V:V").getValues().map(function(row) {return row[0];});
colJ.forEach(function(value, rowI) {
if (value === "rejected" && a < v) {
sheet.hideRows(rowI + 1, 1);
}
else if (value === "withdrew" && a < v) {
sheet.hideRows(rowI + 1, 1);
}
});
colL.forEach(function(value, rowI) {
if (value === "rejected" && b < v) {
sheet.hideRows(rowI + 1, 1);
}
else if (value === "withdrew" && b < v) {
sheet.hideRows(rowI + 1, 1);
}
});
colN.forEach(function(value, rowI)
{
if (value === "rejected" && c < v) {
sheet.hideRows(rowI + 1, 1);
}
else if (value === "withdrew" && c < v) {
sheet.hideRows(rowI + 1, 1);
}
});
colP.forEach(function(value, rowI) {
if (value === "rejected" && d < v) {
sheet.hideRows(rowI + 1, 1);
}
else if (value === "withdrew" && d < v) {
sheet.hideRows(rowI + 1, 1);
}
});
colR.forEach(function(value, rowI) {
if (value === "rejected" && e < v) {
sheet.hideRows(rowI + 1, 1);
}
else if (value === "withdrew" && e < v) {
sheet.hideRows(rowI + 1, 1);
}
});
colT.forEach(function(value, rowI) {
if (value === "rejected" && f < v) {
sheet.hideRows(rowI + 1, 1);
}
else if (value === "withdrew" && f < v) {
sheet.hideRows(rowI + 1, 1);
}
});
colV.forEach(function(value, rowI) {
if (value === "accepted" && g < v) {
sheet.hideRows(rowI + 1, 1);
}
else if (value === "declined" && g < v) {
sheet.hideRows(rowI + 1, 1);
}
else if (value === "didn't extend" && g < v) {
sheet.hideRows(rowI + 1, 1);
}
});
}
}
Original look of sheet
Intended Look of sheet
Since nobody dares to dive deep into this problem (me included) for now, here is the partial solution.
This function returns true if a given date doesn't belong to current quarter:
function is_the_date_old_enough(checked_date) {
// which quarter the date belongs
const get_quarter_of = date => Math.ceil((date.getMonth()+1)/3);
// number of quarters in current date
var cur_date = new Date();
var cur_date_years = cur_date.getFullYear();
var cur_date_quarts = cur_date_years * 4 + get_quarter_of(cur_date);
// number of quarters in checked date
var checked_date_years = checked_date.getFullYear();
var checked_date_quarts = checked_date_years * 4 + get_quarter_of(checked_date);
// if the difference bigger than zero
return (cur_date_quarts - checked_date_quarts) > 0;
}
// tests (current date: 2022-01-14)
console.log(is_the_date_old_enough(new Date())); // false always
console.log(is_the_date_old_enough(new Date('2021-12-20'))); // true
console.log(is_the_date_old_enough(new Date('2021-09-05'))); // true
console.log(is_the_date_old_enough(new Date('2022-01-05'))); // false
console.log(is_the_date_old_enough(new Date('2000-01-05'))); // true
console.log(is_the_date_old_enough(new Date('2030-01-05'))); // false
Beware, the timezones can get you a headache for dates around first and last days of month. If you need to handle timezones it may require a more complicated solution. I suspect the variable cur_date should be defined with '00:00:00.00' time or something like that.
I have a code that I use to log temperatures into Google sheets..Code written in Appsscript. In this code, i want to add a function in the case 'temperature' that can send mail in case the incoming temperature to be logged is more than 8.. How can I do that? Someone help in that kind of code?
function doGet(e) {
Logger.log( JSON.stringify(e) );
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else {
var sheet_id = '1hKXZEIx160TwXi5yUztGBDijNaGgAOjKWSmY-Mowo9M'; // Spreadsheet ID
//var sheetActive = SpreadsheetApp.openById("ID");
//var sheet = sheetActive.getSheetByName("Name");
var sheetActive = SpreadsheetApp.openById(sheet_id);
var sheet = sheetActive.getSheetByName("Theatre");
//var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet().getSheetByName("Sheet3");
var newRow = sheet.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "Africa/Nairobi", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'temperature':
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
// if(){
// }
break;
// case 'humidity':
// rowData[3] = value; // Humidity in column D
// result += ' ,Humidity Written on column D';
// break;
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}
Email Sent if value greater than 8
function doGet(e) {
Logger.log( JSON.stringify(e) );
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else {
var sheet_id = '1hKXZEIx160TwXi5yUztGBDijNaGgAOjKWSmY-Mowo9M'; // Spreadsheet ID
//var sheetActive = SpreadsheetApp.openById("ID");
//var sheet = sheetActive.getSheetByName("Name");
var sheetActive = SpreadsheetApp.openById(sheet_id);
var sheet = sheetActive.getSheetByName("Theatre");
//var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet().getSheetByName("Sheet3");
var newRow = sheet.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "Africa/Nairobi", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'temperature':
Logger.log(
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
Logger.log(`Date: ${new Date()} Value:${value}`);//Please add this
if(parseInt(value) > 8){
GmailApp.sendEmail('recipient emal','Subject',"message");
}
break;
// case 'humidity':
// rowData[3] = value; // Humidity in column D
// result += ' ,Humidity Written on column D';
// break;
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}
GmailApp.sendEmail()
I have a container bound script which sends the query result perfectly.
function doGet(e) {
var ss = SpreadsheetApp.getActive();
var fn = e.parameter.FN;
var key = e.parameter.KEY;
if ( fn == 'CSA' ) {
var sh = ss.getSheetByName("SubmittedAnswers");
var data_raw = e.parameter.DATA.toString().replace("\n ", String.fromCharCode(10));
var data = data_raw.split('|||| ');
sh.appendRow(data);
return ContentService.createTextOutput("New record created");
}
else if ( fn == 'QQ' ) {
var sh = ss.getSheetByName("QuestionBank");
var rg = sh.getDataRange().getValues();
var rgq = sh.getName() + "!" + sh.getDataRange().getA1Notation();
var sql = "Select A, B, C, D, E, F WHERE G IS NOT NULL";
var qry = '=query(' + rgq + ';\"' + sql + '\";1)';
var ts = ss.insertSheet();
var setQuery = ts.getRange(1,1).setFormula(qry);
var getResult = ts.getDataRange().getValues();
ss.deleteSheet(ts);
return ContentService.createTextOutput(JSON.stringify(getResult));
}
}
Now i'm trying to add something like a password so that without this none can run the script. I've tried the code below.
else if ( fn == 'QQ' ) {
var sheet_key = ss.getSheetByName("DashBoard").getRange(9,2).getValue;
if (sheet_key == key) {
var sh = ss.getSheetByName("QuestionBank");
var rg = sh.getDataRange().getValues();
var rgq = sh.getName() + "!" + sh.getDataRange().getA1Notation();
var sql = "Select A, B, C, D, E, F WHERE G IS NOT NULL";
var qry = '=query(' + rgq + ';\"' + sql + '\";1)';
var ts = ss.insertSheet();
var setQuery = ts.getRange(1,1).setFormula(qry);
var getResult = ts.getDataRange().getValues();
ss.deleteSheet(ts);
return ContentService.createTextOutput(JSON.stringify(getResult));
}
}
The sheet_key is perfectly in the "DashBoard" sheet at cell (9,2). Still the script is not returning anything. If i remove the IF part the script works fine :(
What should I do?
This var sheet_key = ss.getSheetByName("DashBoard").getRange(9, 2).getValue;
needs to be this: var sheet_key = ss.getSheetByName("DashBoard").getRange(9, 2).getValue();
This is something that is easy to do with the current editor
I want to randomize D:E, F:G, H:I, J:K if C is 4 with google apps script.
At the moment I use this inefficient & time-consuming code:
function shuffleAnswers() {
var arr = [0, 2, 4, 6];
for (var i = 2; i < lastRow()+1; i++)
{
var amount = sheet().getRange(i,3).getValue();
if (amount == 4)
{
var source = sheet().getRange(i,4,1,2);
var column = 4 + arr[(Math.random() * arr.length) | 0];
var destination = sheet().getRange(i,column,1,2);
var valuesSource = source.getValues();
var valuesDestination = destination.getValues();
source.setValues(valuesDestination);
destination.setValues(valuesSource);
}
}
arr = [-2, 0, 2, 4];
for (var i = 2; i < lastRow()+1; i++)
{
var amount = sheet().getRange(i,3).getValue();
if (amount == 4)
{
var source = sheet().getRange(i,6,1,2);
var column = 6 + arr[(Math.random() * arr.length) | 0];
var destination = sheet().getRange(i,column,1,2);
var valuesSource = source.getValues();
var valuesDestination = destination.getValues();
source.setValues(valuesDestination);
destination.setValues(valuesSource);
}
}
arr = [-4, -2, 0, 2];
for (var i = 2; i < lastRow()+1; i++)
{
var amount = sheet().getRange(i,3).getValue();
if (amount == 4)
{
var source = sheet().getRange(i,8,1,2);
var column = 8 + arr[(Math.random() * arr.length) | 0];
var destination = sheet().getRange(i,column,1,2);
var valuesSource = source.getValues();
var valuesDestination = destination.getValues();
source.setValues(valuesDestination);
destination.setValues(valuesSource);
}
}
arr = [-6, -4, -2, 0];
for (var i = 2; i < lastRow()+1; i++)
{
var amount = sheet().getRange(i,3).getValue();
if (amount == 4)
{
var source = sheet().getRange(i,10,1,2);
var column = 10 + arr[(Math.random() * arr.length) | 0];
var destination = sheet().getRange(i,column,1,2);
var valuesSource = source.getValues();
var valuesDestination = destination.getValues();
source.setValues(valuesDestination);
destination.setValues(valuesSource);
}
}
}
Do you have an idea? Maybe with range.randomize()? Every row with C=4 should be randomized. The columns for multiple rows should not be changed to the same position.
Why so slow?
Use of getValues inside the loop slows down the script considerably. Batching up operations is important.
Script Flow:
Create a random array of numbers between 1 to 8 like, [[1,2,5,6,3,4,7,8]] and then use those numbers as indexes for the new row.
Get all values from the sheet and rearrange only rows where C=4 and set back all values in one shot.
Sample script:
/* Create a Random arrray of numbers from 1 to 8 with couples
* eg:[1,2,5,6,3,4,7,8]*/
const doubleShuffleFix = (n = 4) => {
const generator = function*() {//TODO: boilerplate- can be avoided
let i = 1;
yield i;
while (true) {
if (i < (n - 1) * 2) {
yield (i += 2);
} else {
break;
}
}
};
const available = [...generator()];
//Durstenfeld algo
for (let i = available.length - 1; i > 0; i--) {
let rand = Math.floor(Math.random() * i);
[available[i], available[rand]] = [available[rand], available[i]];
}
return available.map(num => [num, ++num]).flat();
};
function shuffleAnswer() {
const s = SpreadsheetApp.getActive().getSheetByName('Sheet1'),
rg = s.getRange(2, 3, s.getLastRow() - 1, 9),
values = rg.getValues();
rg.setValues(
values.map(row => {
if (row[0] === 4) {
return [4, ...doubleShuffleFix().map(num => row[num])];
}
return row;
})
);
}
References:
Best practices
Durstenfeld algorithm