I'm trying to write a script to put data in specific lines based on the id.
I already have that:
function copy(){
var tabelle1=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var tabelle2=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2 ");
tabelle2.getRange(3,7).copyTo(tabelle1.getRange(tabelle1.getLastRow()+1,1));
tabelle2.getRange(13,4).copyTo(tabelle1.getRange(tabelle1.getLastRow()+0,2));
}
image for the code
Now my question is how can I delete all lines with the same id (1) before copying the lines with the script. (See picture)
Or if my list has each id only once, how can I override the value?
The following should do it. Your code was incorrect in its sheet references. I used setValue instead of copyTo since you need the value selected to pass to the readRows function it just seems cleaner.
function copy(){
var tabelle1=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var tabelle2=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var sel=tabelle1.getRange(3,7).getValue()
readRows(sel)
tabelle2.getRange(tabelle2.getLastRow()+1,1).setValue(sel);
var tm=tabelle1.getRange(13,4).getValue()
tabelle2.getRange(tabelle2.getLastRow()+0,2).setValue(tm);
}
function readRows(sel) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var lr=sheet.getLastRow()
var values = sheet.getRange(1,1,lr,2).getValues();
var rowsDeleted = 0;
for (var i = 0; i <= values.length-1; i++) {
var row = values[i][0];
if (row == sel) {
sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
rowsDeleted++;
}
}
};
Related
I'm trying to write a script where an automatic email is sent to a specific person upon edit of a cell and the cell equals "Done". However, I want the subject to be the first cell of the edited row. Cell that will contain "Done" is always going to be in the AA Column, and I want the subject to be the A column of the same row. Ex: AA3 was edited so subject is A3. I have spent hours sifting through tutorials and came up with this:
function checkValue() {
var sp = PropertiesService.getScriptProperties();
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Accts");
var valueToCheck = sheet.getRange("AA2:AA1000").getValue();
if (valueToCheck = 'Done') {
MailApp.sendEmail("a***a#gmail.com", activeCell.offset(-26,0).getValue(), Email.html);
}
}
Am I doing this entirely wrong or is there hope?
EDIT:
Now that it's resolved. I thought I'd share what my script ended up looking like. I added a UI and an option to execute using a menu option. Hope this helps someone else.
function onEdit(e)
{
var editRange = { // AA2:AA1000
top : 2,
bottom : 1000,
left : 27,
right : 27
};
// Exit if we're out of range
var thisRow = e.range.getRow();
if (thisRow < editRange.top || thisRow > editRange.bottom) return;
var thisCol = e.range.getColumn();
if (thisCol < editRange.left || thisCol > editRange.right) return;
var thisthang = e.value;
var doit = 'TRUE'
// We're in range; timestamp the edit
if(thisthang == doit)
{
doFinish();
}
else{return};
}
function onOpen()
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Finished')
.addItem('Finish', 'doFinish')
.addToUi();
}
function doFinish()
{
var cell = SpreadsheetApp.getActiveSheet().getActiveCell();
var row = cell.getRow();
var Campaign = getCampaignFromRow(row, 1);
var ui = SpreadsheetApp.getUi();
var response = ui.alert('Finish '+Campaign.name+'?', ui.ButtonSet.YES_NO);
if(response == ui.Button.YES)
{
handleFinish(row, Campaign);
}
if(response == ui.Button.NO)
{
SpreadsheetApp.getActiveSheet().getRange(row, 27).setValue('FALSE');
}
}
function getCampaignFromRow(row)
{
var values = SpreadsheetApp.getActiveSheet().getRange(row, 1).getValues();
var rec = values[0];
var Campaign =
{
Campaign_Name: rec[0]
};
Campaign.name = Campaign.Campaign_Name;
return Campaign;
}
function handleFinish(row, Campaign)
{
var templ = HtmlService
.createTemplateFromFile('Campaign-email');
templ.Campaign = Campaign;
var message = templ.evaluate().getContent();
MailApp.sendEmail({
to: "a***a#gmail.com",
subject: "A Campaign has been finished!",
htmlBody: message
});
SpreadsheetApp.getActiveSheet().getRange(row, 27).setValue('TRUE');
}
You are trying to trigger an email when the spreadsheet is edited on the "Accts" sheet, in Column "AA" and the value = "Done".
The best solution is to use an onEdit trigger and also make use of Event Objects. In the case, "a simple trigger cannot send an email" ref, so you will need to create an Installable Trigger.
The main differences to your script are:
- var valueToCheck = sheet.getRange("AA2:AA1000").getValue();
- a couple of things here.
- 1) you are trying to get all the values in the column, but you use the getValue (the method for a single cell) instead of getValues.
- 2) you could have defined the ActiveCell and just returned that value
- 3) though you tried to get the values for the entire column, your if statement is designed as though there is a single value rather than an array of values.
- 4) This demonstrates the benefit of the using the Event Objects. You can succinctly get the values of the edited cell and sheet.
- in your if comparison, you use "="; this is only used to assign a value. When comparing values you must use "==" or "===".
- To get the value of the "subject", the script uses the row number derived from the Event Objects; compared to the offset in your script - they are both acceptable. I used the getRange to demonstrate the alternative.
- your email body was defined as "Email.html", but this isn't declared. The answer uses a very simple body but could just as easily use another solution.
function so5967209001(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet()
// establish the values to be checked
var checkSheetname = "Accts"
var checkValue = "Done"
var checkColumn = 27; // column AA
// this will return the event objects
//Logger.log(JSON.stringify(e)); // DEBUG
// variables to use for checking
var editedrange = e.range;
var editedrow = editedrange.getRow();
var editedcolumn = editedrange.getColumn();
var editedsheet = editedrange.getSheet().getSheetName();
var editedvalue = e.value;
//Logger.log("DEBUG: row = "+editedrow+", column = "+editedcolumn+", sheet = "+editedsheet+", value"+editedvalue)
// test the sheet, the column and the value
if (editedsheet ==checkSheetname && editedcolumn==checkColumn && editedvalue == checkValue){
//Logger.log("DEBUG: this is a match");
var subject = sheet.getRange(editedrow,1).getValue(); // Column A of the edited row
//Logger.log("DEBUG: email subject = "+subject);
// build your own body
var body = "this is the body of the email"
// send the email
MailApp.sendEmail("ejb#tedbell.com.au", subject, body);
//Logger.log("DEBUG: mail sent")
}else{
//Logger.log("DEBUG: this isn't a match");
}
}
I am getting this error: TypeError: Cannot call method "getName" of null. I have used a script to replace the formulas of the active sheet with the cell values. However, I don't want to accidentally run this on a few sheets, so I want to be able to exclude or include only specific sheets. I have been following another post and came up with this, and now I have the error:
function freezeValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
//loop through all sheets and get name to see if it includes specific string
for (i = 0; i < sheets.length; i++) {
var sheet = ss.getSheetByName(sheets[i]);
var name = sheet.getName();
if (name.includes("String_00")) {
//get active sheet and replace range with values
var sheetActive = ss.getActiveSheet();
var range = sheetActive.getRange("A1:Z50");
range.copyTo(range, {contentsOnly: true});
} else {
continue;
//skip over all those that don't meet the condition
}
}
}
UPDATE:
Trying this:
function freezeValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
//loop through all sheets and get name to see if it includes specific string
for (i = 0; i < sheets.length; i++) {
//var sheet = ss.getSheetByName(sheets[i]);
var name = sheets[i].getName().toString();
if (name.indexOf("String_00") > -1) {
//get active sheet and replace range with values
//var sheetActive = ss.getActiveSheet();
var range = sheets.getRange("A1:Z50");
range.copyTo(range, {contentsOnly: true});
} else {
continue;
//skip over all those that don't meet the condition
}
}
}
But now it doesn't do anything. using .include was giving me an error, so I moved over to .indexOf() > -1. Does not freeze data as expected for any sheet, regardless of name.
I came up with 2 solutions for this, sort of started from the drawing board. One creates an array, a sort of blacklist, and then if the sheet name contains any item in the blacklist, then it returns and doesn't execute the replacement. The second solution searches for a pattern in the sheet name and only then continues on to the replacement. Both accomplish what I was trying to do. I think the code I found was a bit buggy and was a bit complicated for what I was doing. I didn't need to loop through all sheet names, just check the sheet name against given variables. Anyway, here they are:
This one creates the array blacklist of pages not to edit:
function freezeValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ['Sheet1', 'Sheet2', 'Sheet3', 'Sheet4'];
var sheetActive = ss.getActiveSheet();
if (sheets.indexOf(sheetActive.getName()) > -1) return;
var range = sheetActive.getRange("A1:Z50");
range.copyTo(range, {contentsOnly: true});
}
This one only searches for specific text in the sheet name before proceeding with the replacement.
function freezeValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetActive = ss.getActiveSheet();
var name = sheetActive.getName()
if (name.indexOf("String_00") > -1) {
var range = sheetActive.getRange("A1:Z50");
range.copyTo(range, {contentsOnly: true});
}
}
I'm sure there is a method to use sheet index value so if you want to skip the first 4 sheets, you can probably do that as well, so it doesn't call on names at all.
UPDATE
function freezeValues2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetActive = ss.getActiveSheet();
if (sheetActive.getIndex() > 4) {
var range = sheetActive.getRange("A1:Z50");
range.copyTo(range, {contentsOnly: true});
}
}
screenshot
Hi all, i need help and i am not a coder. I am trying to achieve the same thing on sheet number 2.
My datas are imported through "=Submission!$b2" from sheet 1
i need help removing rows automatically when a specific cell on column H does not contain the value "Bekreft", i tried both codes shown here with no success.
This is what i added for script:
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('DATA - Do Not Touch!!!'); // change to your own
var values = s.getDataRange().getValues();
for(var i=values.length;i>0;i-=1){
var lcVal=values[i-1][0].toLowerCase() //Change to all lower case
var index = lcVal.indexOf("vent"); //now you only have to check for contains "vent"
if (lcVal.indexOf("vent") > -1){
s.deleteRow(i)};
}}
Seeing as you state you are "not a coder", and the code you pasted will not help you if you are referencing data from another page, I would suggest using a filter function to achieve your goal. You would add the following formula to your second page:
=FILTER(Submission!B:B,ISNUMBER(SEARCH("Bekreft", Submission!H:H)))
If you are looking to have a script go through your static list and delete out values that do not contain "Bekreft" then you can use the following script.
function onEdit() {
var sheet = SpreadsheetApp.openById("Add Sheet ID").getSheetByName('Sheet1');
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var rowsDeleted = 0;
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
//row for condition
if (row[7].indexOf("Bekreft")) {
sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
rowsDeleted++;
}
}
};
var wRoot = new ctypes.unsigned_long();
var wParent = new ctypes.unsigned_long();
var wChild = new ctypes.unsigned_long.ptr();
var nChildren = new ctypes.unsigned_int();
var rez = XQueryTree(_disp, w, wRoot.address(), wParent.address(), wChild.address(), nChildren.address())
if(rez != 0) { //can probably test this against `None` instead of `0`
var nChildrenCasted = ctypes.cast(nChildren, ctypes.unsigned_int).value;
for(var i=0; i<nChildrenCasted; i++) {
searchForPidStartingAtWindow(wChild[i]);
}
} else {
console.warn('this window has no children, rez:', rez);
}
I sucessfully get the nChildrenCasted it's 94.
However I can't access wChild elements, it should be an array
So problem is on the line: searchForPidStartingAtWindow(wChild[i]);
how to pass wChild[i]?
I tried:
var wChildCasted = ctypes.cast(wChild, ctypes.unsigned_long).contents;
console.log('wChildCasted:', wChildCasted);
I'm pretty sure its along those lines but i cant figure it out
full code, can be copy pasted and run from scratchpad:
https://gist.github.com/Noitidart/224f8999eb26ec52894f
You need to cast from the raw pointer type to an ArrayType pointer:
var wChildCasted = ctypes.cast(wChild, ctypes.ArrayType(ctypes.unsigned_long, nChildrenCasted).ptr).contents;
here the file
https://docs.google.com/spreadsheet/ccc?key=0AurtxTJwggIpdG9GaE1TOV9wMEw2UHhjZVJyUXVETUE
you'll find on sheet Key, what is meant to do :
Find in all sheets, first in column B the row where the reference (Key!B1) stands, then starting from this row, find in column C where the reference (Key!B2) stands for first
in other words, we are looking for the couple and make the cell in column C as activecell
the script is working in debug mode, only
running it using the button in sheet Key, make it "not select" the good cell, even if the cell to be selected is found (logged in Logger)
I use a color function
That mean, blue or red is the cell to be selected , and sometimes it's not selected
the code :
function lookFor() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var referSheet=ss.getSheetByName("Key");
var sheetToCheck = new Array;
sheetToCheck[0]=ss.getSheetByName("work");
sheetToCheck[1]=ss.getSheetByName("user");
sheetToCheck[2]=ss.getSheetByName("tax");
sheetToCheck[3]=ss.getSheetByName("cont");
sheetToCheck[4]=ss.getSheetByName("ind");
var referenceB=referSheet.getRange("B1").getValue();
var referenceC=referSheet.getRange("B2").getValue();
//loop to work with all reference as long as there are data in the column A
for (j in sheetToCheck){
sheetToCheck[j].setActiveCell("A1");
var dataToCheck=new Array;
dataToCheck=sheetToCheck[j].getRange(1,2,sheetToCheck[j].getLastRow(),2).getValues();
for (i in dataToCheck){
var done=false;
if (dataToCheck[i][0]==referenceB){
for (k=i;k<dataToCheck.length;k++){
if (dataToCheck[k][1]==referenceC){
//this part is user to change the color of the cell, to check if the code is working well
if (sheetToCheck[j].getRange(parseInt(k)+1,3,1,1).getBackgroundColor()=="red"){
sheetToCheck[j].getRange(parseInt(k)+1,3,1,1).setBackgroundColor("blue");
}
else
{
sheetToCheck[j].getRange(parseInt(k)+1,3,1,1).setBackgroundColor("red");
}
var cell=sheetToCheck[j].getRange(parseInt(k)+1,3,1,1).getA1Notation() ;
sheetToCheck[j].setActiveCell(cell);
SpreadsheetApp.flush();
done=true;
Logger.log("Sheet :"+sheetToCheck[j].getName()+" - Cell :"+cell);
break;
}
}
if (done==true){
break;
}
}
}
}
}
enter code here
I noticed you aready fixed this in your script:
var referenceB=referSheet.getRange("B1").getValue(); //A2
var referenceC=referSheet.getRange("B2").getValue(); //B2
Here is a shorter version of your code :)
function LookForCity() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var referSheet = ss.getSheetByName("Key").getDataRange().getValues()[1];
var sheetName = ["work", "user", "tax", "cont", "ind"];
for (j in sheetName){
var sheet = ss.getSheetByName(sheetName[j]);
var values = sheet.getDataRange().getValues();
for(i in values){
if(values[i][1] == referSheet[0] && values[i][2] == referSheet[1]){
Logger.log('Sheet: ' + sheetName[j]+ ' Cell: C'+(parseInt(i)+1) );
sheet.setActiveCell(sheet.getRange(parseInt(i)+1, 3));
Utilities.sleep(3000);
break;
}
}
}
}