How to delete specific cells with app script? - google-apps-script

My intention is to be able to delete for example cell F1 without deleting cell F2.
var sheet = ss.getSheetByName("Questionário DQSA");
var range = sheet.getRange("B1:U1");
range.clearContent();
Here I clear the content of these cells but I would like to know how to delete them.

You can use Range.deleteCells(Dimension):
var sheet = ss.getSheetByName("Questionário DQSA");
var range = sheet.getRange("F1");
range.deleteCells(SpreadsheetApp.Dimension.COLUMNS);//F2 becomes the new F1

If you want to roll your own:
function deleteCell(shift) {
var shift=shift || "left"; //left or up
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var cell=ss.getActiveCell();
if(shift=="left") {
var rg=sh.getRange(cell.getRow(),1,1,sh.getLastColumn());
var vA=rg.getValues();
var row=vA[0];
row.splice(cell.getColumn()-1,1);
rg.clearContent();
sh.getRange(cell.getRow(),1,1,row.length).setValues([row]);
}
if(shift=="up") {
var rg=sh.getRange(1,cell.getColumn(),sh.getLastRow(),1);
var vA=rg.getValues();
var row=vA.map(function(r){return r[0]});
row.splice(cell.getRow()-1,1);
var col=[];
row.forEach(function(e){
col.push([e]);
});
rg.clearContent();
sh.getRange(1,cell.getColumn(),col.length,1).setValues(col);
}
}
Of course now that I know about that new method in range it's a lot easier to write. Thanks to #TheMaster
function deleteCell(shift) {
var shift=shift || "left";
var ss=SpreadsheetApp.getActive();
var cell=ss.getActiveCell();
if(shift=="left") {
cell.deleteCells(SpreadsheetApp.Dimension.COLUMNS);
}
if(shift=="up") {
cell.deleteCells(SpreadsheetApp.Dimension.ROWS);
}
}

Related

Apps Script: Move duplicates to another sheet instead of deleting them

I found this amazing masterpiece of #Cooper to search for duplicates based on values in 1 column. Now instead of removing these duplicates as the code does, I want to move them to another sheet. Any idea how this can be done?
Thanks :).
Here is the code:
function removeDuplicates() {
var sh=SpreadsheetApp.getActiveSheet();
var dt=sh.getDataRange().getValues();
var uA=[];
var d=0;
for(var i=0;i<dt.length;i++) {
if(uA.indexOf(dt[i][0])==-1) {
uA.push(dt[i][0]);
}else{
sh.deleteRow(i+1-d++);
}
}
}
Move row
function removeDuplicates() {
const ss = SpreadsheetApp.getActive();
const dsh = ss.getSheetByName('Destination');
var sh=SpreadsheetApp.getActiveSheet();
var dt=sh.getDataRange().getValues();
var uA=[];
let d = 0;
for(var i=0;i<dt.length;i++) {
if(uA.indexOf(dt[i][0])==-1) {
uA.push(dt[i][0]);
}else{
dsh.appendRow(dt[i]);//append
sh.deleteRow(i+1-d++);//delete
}
}
}

Matching cell values in different Google Sheets

Users input text in cell A1 of sheet1. I want to find an exact match in column G of sheet2, and get the row of that match. I'm new to GAPS and wrote a script to find matches all on one sheet. How do I modify it to look at sheet2?
function rowOfMatch(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = sheet.getDataRange().getValues();
var inputName = sheet.getRange("A1").getValue();
for(var i = 0; i<data.length;i++){
if(data[i][6] == inputName){ //[6] to search column G
Logger.log((i+1))
return i+1;
}
}
}
function runOne(){
var ss=SpreadsheetApp.getActive();
var sh1=ss.getSheetByName('Sheet1');
var sh2=ss.getSheetByName('Sheet2');
var rg1=sh1.getRange(1,1,sh1.getLastRow(),1);
var rg2=sh2.getRange(1,7,sh2.getLastRow(),1);
var v1=rg1.getValues();
var v2=rg2.getValues().map(function(r){return r[0];});
for(var i=0;i<v1.length;i++) {
var row=v2.indexOf(v1[i][0])+1;
if(row>0) {
sh1.getRange(i+1,2).setValue(row);
}else{
sh1.getRange(i+1,2).setValue('Not Found');
}
}
}
Animation:

How to get the cell position of a button or rather how to get a variable for the execution of a button?

With the function I woud like to do the following:
Flow
1.) Get the current User ID
2.) Finding the user's lines where the states are on the alert icon
3.) Change the date in column K to the current date using the format "dd.MM.yyyy"
4.) Generate a time stamp in column L using the format "HH:mm:ss"
5.) Generate a time stamp in the column P using the format "dd.MM.yyyy' 'HH:mm"
Therefore I used the code below.
Unfortunately the code doesn't work. I did not got any error.
What am I doing wrong?
function CheckAll(){
var userID=getUserId();
if(userID) {
var timezone = "GMT+2";
var TimestampFormat1 = "dd.MM.yyyy' 'HH:mm";
var TimestampFormat2 = "HH:mm:ss";
var ss=SpreadsheetApp.getActiveSpreadsheet();
var tickerCheck=ss.getSheetByName('WATCHLIST-Pflege');
var State=tickerCheck.getRange("O1:O2").getCell(2,1).getValues();
var startRow=16;
var lastRow=tickerCheck.getLastRow()-startRow+1;
var rngStateCheck=tickerCheck.getRange(startRow,15,lastRow,1);
var StateCheck=rngStateCheck.getValues();
var userIds=tickerCheck.getRange(startRow,1,lastRow,1).getValues();
var rngLastCheck=tickerCheck.getRange(startRow,11,lastRow,1);
var rngTimeStamp1=tickerCheck.getRange(startRow,12,lastRow,1);
var rngTimeStamp2=tickerCheck.getRange(startRow,16,lastRow,1);
var date=new Date();
for(var i=0;i<StateCheck.length;i++){
if(StateCheck[i][14]==State && userIds[i][0]==userID){
rngLastCheck.getCell(i+1, 1).setValue(date);
rngTimeStamp1.getCell(i+1, 1).setValue(Utilities.formatDate(date, timezone, TimestampFormat2));
rngTimeStamp2.getCell(i+1, 1).setValue(Utilities.formatDate(date, timezone, TimestampFormat1));
}
}
}else{
SpreadsheetApp.getUi().alert('Falsche User ID');
}
}
function getUserId() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Startseite');
var rg=sh.getRange(35,3,sh.getLastRow()-3,3);
var vA=rg.getValues();
var userEmail=Session.getEffectiveUser().getEmail();
for(var i=0;i<vA.length;i++) {
if(vA[i][0]==userEmail) {
return vA[i][1];
break;
}
}
return null;
}
I solved the problem by adding the variable var StateToCheck=StateCheck[i][0] to the for loop.
Now the code looks like this:
function CheckAll(){
var userID=getUserId();
if(userID) {
var timezone = "GMT+2";
var TimestampFormat1 = "dd.MM.yyyy' 'HH:mm";
var TimestampFormat2 = "HH:mm:ss";
var ss=SpreadsheetApp.getActiveSpreadsheet();
var tickerCheck=ss.getSheetByName('WATCHLIST-Pflege');
var State=tickerCheck.getRange("O1:O2").getCell(2,1).getValues();
var startRow=16;
var lastRow=tickerCheck.getLastRow()-startRow+1;
var rngStateCheck=tickerCheck.getRange(startRow,15,lastRow,1);
var StateCheck=rngStateCheck.getValues();
var userIds=tickerCheck.getRange(startRow,1,lastRow,1).getValues();
var rngLastCheck=tickerCheck.getRange(startRow,11,lastRow,1);
var rngTimeStamp1=tickerCheck.getRange(startRow,12,lastRow,1);
var rngTimeStamp2=tickerCheck.getRange(startRow,16,lastRow,1);
var date=new Date();
for(var i=0;i<StateCheck.length;i++){
var StateToCheck=StateCheck[i][0]
if((StateToCheck==State)&&(userIds[i][0]==userID)){
rngLastCheck.getCell(i+1, 1).setValue(date);
rngTimeStamp1.getCell(i+1, 1).setValue(Utilities.formatDate(date, timezone, TimestampFormat2));
rngTimeStamp2.getCell(i+1, 1).setValue(Utilities.formatDate(date, timezone, TimestampFormat1));
}
}
}else{
SpreadsheetApp.getUi().alert('Falsche User ID');
}
}
function getUserId() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Startseite');
var rg=sh.getRange(35,3,sh.getLastRow()-3,3);
var vA=rg.getValues();
var userEmail=Session.getEffectiveUser().getEmail();
for(var i=0;i<vA.length;i++) {
if(vA[i][0]==userEmail) {
return vA[i][1];
break;
}
}
return null;
}
You could use this approach:
function CheckAll1(){
var userID=getUserId();
if(userID) {
var ss=SpreadsheetApp.getActive();
var tsh=ss.getSheetByName('Tickerprüfung');
var startRow=12;
var lastRow=tsh.getLastRow()-startRow+1;
var range=tsh.getRange(startRow,12,tsh.getLastRow()-startRow+1,1);
var tvA=range.getValues();
var userIds=tsh.getRange(startRow,1,tsh.getLastRow()-startRow+1,1).getValues();
var lcrg=tsh.getRange(startRow,9,tsh.getLastRow()-startRow+1,1);
var tsrg=tsh.getRange(startRow,10,tsh.getLastRow()-startRow+1,1);
var today=new Date();
var dateInMs=new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime();
for(var i=0;i<tvA.length;i++){
var nextDate=new Date(tvA[i][0]);
if(Object.prototype.toString.call(nextDate) === '[object Date]' && userIds[i][0]==userID) {
if(dateInMs>=nextDate.getTime()){
lcrg.getCell(i+startRow, 1).setValue(today);
tsrg.getCell(i+startRow, 1).setValue(new Date().toLocaleTimeString());
}
}
}
}else{
SpreadsheetApp.getUi().alert('Invalid UserId');
}
}
function getUserId() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Startseite');
var rg=sh.getRange(20,2,sh.getLastRow()-19,2);
var vA=rg.getValues();
var userEmail=Session.getEffectiveUser().getEmail();
for(var i=0;i<vA.length;i++) {
if(vA[i][0]==userEmail) {
return vA[i][1];
break;
}
}
return null;
}
And then in the Startseite sheet you could associate user emails with UserId's in this way.
Look closely at the code as I have corrected some errors pertaining to the calculation of rows that did not account for startRow=12 also third parameter in a range is the number of rows not the last row.

Appending multiple rows from a source sheet to a destination sheet in Google Sheets

I am using code from this older thread to copy a range of cells from a source sheet and paste them to the last row of a destination sheet.
https://support.google.com/docs/forum/AAAABuH1jm04B0WxqiEJns/?hl=en&gpf=%23!topic%2Fdocs%2F4B0WxqiEJns
The suggested code copies and pastes the data on the same sheet so I attempted (and failed) to modify it:
function appendEagleData() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName("Eagle New Rows");
var dest = ss.getSheetByName("Eagle Static Data")
var source = sh.getRange("A4:J20");
var v = source.getValues();
dest.getRange(dest.getLastRow() + 1, 1, v.length, v[0].length).setValues(v);
}
...Clearly, I'm a little out of my depth. Any help would be appreciated.
function appendEagleData() {
var ss=SpreadsheetApp.getActive();
var sh1=ss.getSheetByName("Eagle New Rows");
var rg1=sh1.getRange(4,1,sh1.getLastRow()-3,10);
var sh2=ss.getSheetByName("Eagle Static Data")
var rg2=sh2.getRange(sh2.getLastRow()+1,1);
rg1.copyTo(rg2);
}
try this:
function appendEagleData() {
var ss=SpreadsheetApp.getActive();
var sh1=ss.getSheetByName("Eagle New Rows");
var rg1=sh1.getRange(4,1,getColumnHeight(2,sh1,ss)-3,10);
var sh2=ss.getSheetByName("Eagle Static Data")
var rg2=sh2.getRange(sh2.getLastRow()+1,1);
rg1.copyTo(rg2);
}
function getColumnHeight(col,sh,ss){
var ss=ss || SpreadsheetApp.getActive();
var sh=sh || ss.getActiveSheet();
var col=col || sh.getActiveCell().getColumn();
var rg=sh.getRange(1,col,sh.getLastRow(),1);
var vA=rg.getValues();
while(vA[vA.length-1][0].length==0){
vA.splice(vA.length-1,1);
}
return vA.length;
}

Set value based on drop down selection using script

Because prices change over time, I don't want to tie in the price permanently to another cell. So I'd like the script to set the price based on drop down selection.
I have Services sheet with Cost column:
I'd like the script to apply the cost based on selection like so (in Selection sheet):
Here's the example spreadsheet:
https://docs.google.com/spreadsheets/d/1O1rZUstDNSXPdUVXvaDfPO4rAQs2cJWHimfGxbddtNU/edit#gid=232108540
How can I set value Cost in Services sheet to Selection sheet with script?
Try this:
function cost() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Services');
var rg=sh.getRange(2,1,sh.getLastRow()-1,2);
var vA=rg.getValues();
var costObj={}
for(var i=0;i<vA.length;i++) {
costObj[vA[i][0]]=vA[i][1];
}
var selsh=ss.getSheetByName('Selection');
var selrg=selsh.getRange(2,1,selsh.getLastRow()-1,2);
var vB=selrg.getValues();
for(var j=0;j<vB.length;j++) {
vB[j][1]=costObj[vB[j][0]];
}
selrg.setValues(vB);
//if you only want to set columnB you can do this instead of the above line
//var vC=vB.map(function(r){return [r[1]]});
//selsh.getRange(2,2,vC.length,1).setValues(vC);
}
As an onEdit():
function cost(e) {//Installable onEdit()
var sh=e.range.getSheet();
var name=sh.getName();
if(name!='Selection')return;
if(e.value && e.range.columnStart==1) {
e.range.offset(0,1).setValue(getCostObj()[e.value]);
}
}
function getCostObj() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Services');
var rg=sh.getRange(2,1,sh.getLastRow()-1,2);
var vA=rg.getValues();
var costObj={}
for(var i=0;i<vA.length;i++) {
costObj[vA[i][0]]=vA[i][1];
}
return costObj;
}