How to add a button per row in google spreadsheet? - google-apps-script

I have a simple spreadsheet with multiple rows I want to add button to each of it automatically.
On click this button will remove the entire row and move it to another spreadsheet.
I've looked online and couldn't find a way to add buttons to spreadsheets. Some people suggest to insert drawings and assign macros, but looks like the latest version lacks this feature.
I've also read about google app sript. I was able to add buttons to a menu, but not directly to each row of a spreadsheet.
Do you have any advice or suggestion on how to better achieve this?

I suggest the you create a column(say 10) at the end of each row with a List Data Validation of "Move Row" and create an onEdit function like so
function onEdit(eventInfo) {
if (eventInfo.range.getColumn() == 10 && eventInfo.value == "Move Row")
{
var ss = eventInfo.source;
var row = eventInfo.range.getRow();
var range = ss.getRange(row, 1, 10) // this is your range, do with it what you will
}
}

So this script is not entirely my own work, but the results of something I was working on with help.
It will look in a source sheet, look at a column you specify (by number), and look for a value in this sheet.
If matched, it will move that row to another sheet, within the spreadshet, of your choosing.
function moveRowInternalSheet()
{
var sourceSheet = "";
var columnNumberToWatch = ;
var valueToFind = "";
var destinationSheet = "";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sourceSheet);
var values = sheet.getDataRange().getValues();
var counter = 1; //starts looking in second row, due to header
var archive = [];
while (counter < values.length)
{
if (values[counter][columnNumberToWatch - 1] == valueToFind)
{
archive.push(values.splice(counter, 1)[0]);
}
else
{
// If the value to find is not found. Then increment the counter by 1
counter++;
}
}
var archiveLength = archive.length;
if (!archiveLength) return;
var targetSheet = ss.getSheetByName(destinationSheet);
var lastRow = targetSheet.getLastRow();
var requiredRows = lastRow + archiveLength - targetSheet.getMaxRows();
if (requiredRows > 0) targetSheet.insertRowsAfter(lastRow, requiredRows);
targetSheet.getRange(lastRow + 1, 1, archiveLength, archive[0].length).setValues(archive);
sheet.clearContents();
sheet.getRange(1, 1, values.length, values[0].length).setValues(values);
}

Related

Google Sheets Script to import data based on cell value and not duplicate information

I need to pull/import data from "sheet 1" to "sheet 2" based on column 4 being a specific text string. The script should not pull lines that already exist.
I have no idea if this is possible. I can pull the data but it just recopies everything so I have duplicates.
Any help would be super appreciated.
function onEdit() {
var ss = SpreadsheetApp.openById('1Ognzsi6C0DU_ZyDLuct58f5U16sshhBpBoQ8Snk8bhc');
var sheet = ss.getSheetByName('Sheet 1');
var testrange = sheet.getRange('D:D');
var testvalue = (testrange.getValues());
var sss = SpreadsheetApp.getActive();
var csh = sss.getSheetByName('Sheet 1');
var data = [];
var j =[];
for (i=0; i<testvalue.length;i++) {
if ( testvalue[i] == 'Dan') {
data.push.apply(data,sheet.getRange(i+1,1,1,11).getValues());
j.push(i);
}
}
csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}
Sheet 1
Sheet 2
Solution
You should be able to replace your code with this and it will work. You would put this script in the target sheet (Sheet 2), and replace the ID in the first line of the function with the origin (Sheet 1).
I'll leave it up to you to change to an onEdit or to make it a menu item. Right now it can be run from the script editor. onEdit doesn't make sense to me as an appropriate trigger. Maybe you prefer a Time-Driven Trigger. Though a custom menu would be the best way IMO.
function pullData() {
var sourceSs = SpreadsheetApp.openById('[YOUR_SPREADSHEET_ID]');
var sourceRange = sourceSs.getSheetByName('Sheet1').getDataRange();
var sourceHeight = sourceRange.getHeight();
var sourceWidth = sourceRange.getWidth();
var sourceData = sourceSs.getSheetByName('Sheet1').getRange(2, 1, sourceHeight - 1, sourceWidth).getValues();
var targetSs = SpreadsheetApp.getActive();
var targetRange = targetSs.getSheetByName('Sheet1').getDataRange();
var targetHeight = targetRange.getHeight();
var targetWidth = targetRange.getWidth();
var sourceDataChecker = [];
var targetDataChecker = [];
sourceData.forEach((row) => {
sourceDataChecker.push(row[0] + row[1] + row[2] + row[3]);
})
if (targetHeight != 1) {
var targetData = sourceSs.getSheetByName('Sheet1').getRange(2, 1, targetHeight - 1, targetWidth).getValues();
targetData.forEach((row) => {
targetDataChecker.push(row[0] + row[1] + row[2] + row[3]);
});
};
sourceData.forEach((row, i) => {
if (!(targetDataChecker.includes(sourceDataChecker[i]))) {
targetSs.appendRow(row);
};
});
}
Explanation
This script builds an "index" of each row in both sheets by concatenating all the values in the row. I did this because I noticed that sometimes you have "joe" in two rows, and so, you can't simply use column 4 as your index. You are basically checking for any row that is different from one in the target sheet (Sheet 2).
If the target sheet is blank, then all rows are copied.
References
Append Row to end of sheet
Get Data Range (range of sheet that contains data)
Get Range Height (to deal with headers)
Get Range Width
for Each

I need to split a Google Sheet into multiple tabs (sheets) based on column value

I have searched many possible answers but cannot seem to find one that works. I have a Google Sheet with about 1600 rows that I need to split into about 70 different tabs (with about 20-30 rows in each one) based on the value in the column titled “room”. I have been sorting and then cutting and pasting but for 70+ tabs this is very tedious.
I can use the Query function but I still need to create a new tab, paste the function and update the parameter for that particular tab.
This script seemed pretty close:
ss = SpreadsheetApp.getActiveSpreadsheet();
itemName = 0;
itemDescription = 1;
image = 2;
purchasedBy = 3;
cost = 4;
room = 5;
isSharing = 6;
masterSheetName = "Master";
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Update Purchases')
.addItem('Add All Rows To Sheets', 'addAllRowsToSheets')
.addItem('Add Current Row To Sheet', 'addRowToNewSheet')
.addToUi();
}
function addRowToNewSheet() {
var s = ss.getActiveSheet();
var cell = s.getActiveCell();
var rowId = cell.getRow();
var range = s.getRange(rowId, 1, 1, s.getLastColumn());
var values = range.getValues()[0];
var roomName = values[room];
appendDataToSheet(s, rowId, values, roomName);
}
function addAllRowsToSheets(){
var s = ss.getActiveSheet();
var dataValues = s.getRange(2, 1, s.getLastRow()-1, s.getLastColumn()).getValues();
for(var i = 0; i < dataValues.length; i++){
var values = dataValues[i];
var rowId = 2 + i;
var roomName = values[room];
try{
appendDataToSheet(s, rowId, values, roomName);
}catch(err){};
}
}
function appendDataToSheet(s, rowId, data, roomName){
if(s.getName() != masterSheetName){
throw new Error("Can only add rows from 'Master' sheet - make sure sheet name is 'Master'");
}
var sheetNames = [sheet.getName() for each(sheet in ss.getSheets())];
var roomSheet;
if(sheetNames.indexOf(roomName) > -1){
roomSheet = ss.getSheetByName(roomName);
var rowIdValues = roomSheet.getRange(2, 1, roomSheet.getLastRow()-1, 1).getValues();
for(var i = 0; i < rowIdValues.length; i++){
if(rowIdValues[i] == rowId){
throw new Error( data[itemName] + " from row " + rowId + " already exists in sheet " + roomName + ".");
return;
}
}
}else{
roomSheet = ss.insertSheet(roomName);
var numCols = s.getLastColumn();
roomSheet.getRange(1, 1).setValue("Row Id");
s.getRange(1, 1, 1, numCols).copyValuesToRange(roomSheet, 2, numCols+1, 1, 1);
}
var rowIdArray = [rowId];
var updatedArray = rowIdArray.concat(data);
roomSheet.appendRow(updatedArray);
}
But I always get an unexpected token error on line 51 or 52:
var sheetNames = [sheet.getName() for each(sheet in ss.getSheets())];
(And obviously the column names, etc. are not necessarily correct for my data, I tried changing them to match what I needed. Not sure if that was part of the issue.)
Here is a sample of my data: https://docs.google.com/spreadsheets/d/1kpD88_wEA5YFh5DMMkubsTnFHeNxRQL-njd9Mv-C_lc/edit?usp=sharing
This should return two separate tabs/sheets based on room .
I am obviously not a programmer and do not know Visual Basic or Java or anything. I just know how to google and copy things....amazingly I often get it to work.
Let me know what else you need if you can help.
Try the below code:
'splitSheetIntoTabs' will split your master sheet in to separate sheets of 30 rows each. It will copy only the content not the background colors etc.
'deleteTabsOtherThanMaster' will revert the change done by 'splitSheetIntoTabs'. This function will help to revert the changes done by splitSheetIntoTabs.
function splitSheetIntoTabs() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var header = rows[0];
var contents = rows.slice(1);
var totalRowsPerSheet = 30; // This value will change no of rows per sheet
//below we are chunking the toltal row we have into 30 rows each
var contentRowsPerSheet = contents.map( function(e,i){
return i%totalRowsPerSheet===0 ? contents.slice(i,i+totalRowsPerSheet) : null;
}).filter(function(e){ return e; });
contentRowsPerSheet.forEach(function(e){
//crate new sheet here
var currSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet();
//append the header
currSheet.appendRow(header);
//populate the rows
e.forEach(function(val){
currSheet.appendRow(val);
});
});
}
// use this function revert the sheets create by splitSheetIntoTabs()
function deleteTabsOtherThanMaster() {
var sheetNotToDelete ='Master';
var ss = SpreadsheetApp.getActive();
ss.getSheets().forEach(function(sheet){
if(sheet.getSheetName()!== sheetNotToDelete)
{
ss.deleteSheet(sheet);
}
});
}
I was using Kessy's nice script, but started having trouble when the data became very large, where the script timed out. I started looking for ways to reduce the amount of times the script read/wrote to the spreadsheet (rather than read/write one row at a time) and found this post https://stackoverflow.com/a/42633934
Using this principle and changing the loop in the script to have a loop within the loop helped reduce these calls. This means you can also avoid the second call to append rows (the "else"). My script is a little different to the examples, but basically ends something like:
`for (var i = 1; i < theEmails.length; i++) {
//Ignore blank Emails and sheets created
if (theEmails[i][0] !== "" && !completedSheets.includes(theEmails[i][0])) {
//Set the Sheet name = email address. Index the sheets so they appear last.
var currentSheet = theWorkbook.insertSheet(theEmails[i][0],4+i);
//append the header
//To avoid pasting formulas, we have to paste contents
headerFormat.copyTo(currentSheet.getRange(1,1),{contentsOnly:true});
//Now here find all the rows containing the same email address and append them
var theNewRows =[];
var b=0;
for(var j = 1; j < rows.length; j++)
{
if(rows[j][0] == theEmails[i][0]) {
theNewRows[b]=[];//Initial new array
theNewRows[b].push(rows[j][0],rows[j][1],rows[j][2],rows[j][3],rows[j][4],rows[j][5],rows[j][6],rows[j][7]);
b++;
}
}var outrng = currentSheet.getRange(2,1,theNewRows.length,8); //Make the output range the same size as the output array
outrng.setValues(theNewRows);
I found a table of ~1000 rows timed out, but with the new script took 6.5 secs. It might not be very neat, as I only dabble in script, but perhaps it helps.
I have done this script that successfully gets each room and creates a new sheet with the corresponding room name and adding all the rows with the same room.
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
// This var will contain all the values from column C -> Room
var columnRoom = sheet.getRange("C:C").getValues();
// This var will contain all the rows
var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
//Set the first row as the header
var header = rows[0];
//Store the rooms already created
var completedRooms = []
//The last created room
var last = columnRoom[1][0]
for (var i = 1; i < columnRoom.length; i++) {
//Check if the room is already done, if not go in and create the sheet
if(!completedRooms.includes(columnRoom[i][0])) {
//Set the Sheet name = room (except if there is no name, then = No Room)
if (columnRoom[i][0] === "") {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet("No Room");
} else {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(columnRoom[i][0]);
}
//append the header
currentSheet.appendRow(header);
currentSheet.appendRow(rows[i]);
completedRooms.push(columnRoom[i][0])
last = columnRoom[i][0]
} else if (last == columnRoom[i][0]) {
// If the room's sheet is created append the row to the sheet
var currentSheet = SpreadsheetApp.getActiveSpreadsheet()
currentSheet.appendRow(rows[i]);
}
}
}
Please test it and don't hesitate to comment for improvements.

Sheets Script to copy parts of a row based on Cell value

So. This should be simple And I can do what I need with (=QUERY(MAIN!A:H, "select A,C,F where H='OPEN'") But I can not sort or edit. So I am trying to make a script that copys over from the "MAIN" tab to the "OPEN" tab Just Column A,C or F when column H is changed to OPEN. I need to put it on a trigger so that the information stays on the open tab and I can edit and sort it. The problem is. I am not great at Scripts and I can not figure out how to do just Column A, C and F. I have so far.
https://docs.google.com/spreadsheets/d/11PfKqDhQnBkDM9qIw3CjVUa9-fOTTVg51TzWzHXUo5w/edit?usp=sharing
function CopyDataToNewFile() {
var sourceSheet = SpreadsheetApp.openById('11PfKqDhQnBkDM9qIw3CjVUa9-fOTTVg51TzWzHXUo5w').getSheetByName('MAIN'),
sourceValues = sourceSheet.getRange(4, 1, sourceSheet.getLastRow(), sourceSheet.getLastColumn()).getValues(),
targetSheet = SpreadsheetApp.openById('11PfKqDhQnBkDM9qIw3CjVUa9-fOTTVg51TzWzHXUo5w').getSheetByName('OPEN');
targetSheet.getRange(targetSheet.getLastRow() + 1, 1, sourceValues.length, sourceValues[0].length).setValues(sourceValues);
sourceSheet.getRange(6, 1, sourceSheet.getLastRow(), sourceSheet.getLastColumn())
}
EDIT:
If you don't want the script to run automatically when the Status column from MAIN is edited, use this function instead:
function CopyDataToNewFile() {
var sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('MAIN');
var values = sourceSheet.getDataRange().getValues();
var targetSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('OPEN');
targetSheet.clear();
for(var i = 1; i < values.length; i++) {
if(values[i][7] == 'OPEN') {
var dataA = values[i][0];
var dataC = values[i][2];
var dataF = values[i][5];
targetSheet.appendRow([dataA, dataC, dataF]);
}
}
}
=========================================
If you want the script to run every time column H is edited, use this below. The script does nothing if the edited cell is from column H from MAIN, so don't worry about an edit in OPEN changing the data from MAIN.
All data is copied to the first 3 columns of the OPEN tab. Also, all previous data in OPEN tab is deleted before getting copied:
function onEdit(e) {
var sourceSheet = e.source.getActiveSheet();
var sheet_name = sourceSheet.getName();
var column = e.range.getColumn();
if(sheet_name == 'MAIN' && column == 8) {
var values = sourceSheet.getDataRange().getValues();
CopyDataToNewFile(values);
}
}
function CopyDataToNewFile(values) {
var targetSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('OPEN');
targetSheet.clear(); // This clears previous data in OPEN tab, delete this line if you don't want this to happen.
// Looping through each row in MAIN tab
for(var i = 1; i < values.length; i++) {
// Checking if column H value is 'OPEN'
if(values[i][7] == 'OPEN') {
// Getting values from A, C, F columns
var dataA = values[i][0];
var dataC = values[i][2];
var dataF = values[i][5];
targetSheet.appendRow([dataA, dataC, dataF]);
}
}
}
I hope this is what you wanted to do, and I'm sorry if I misunderstood your purpose.

How to add new rows when archiving a row in Google Sheets

I currently have working code inside of my Google Sheet. The code moves certain rows in the sheet over to another sheet when labeled as "Archive" in a drop down menu.
The problem I have is that when this happens, the entire row gets deleted. I only need the information from column C:O (C2:O) to be archived. Another problem that this creates, when it deletes the row the other rows move up, thus deleting the set amount of rows I have created for input.
I need it to automatically replace the archive rows with another row with all the same conditional formatting and functions so that it does not disrupt the rest of the sheet and there is no need to go in and manually create more rows.
Please help, thank you very much in advance.
Current code used in Google App Scripts is attached below.
function myFunction() {
// moves a row from a sheet to another when a magic value is entered in a column
// adjust the following variables to fit your needs
// see https://productforums.google.com/d/topic/docs/ehoCZjFPBao/discussion
var sheetNameToWatch = 'Campaigns';
var columnNumberToWatch = 6;
// column A = 1, B = 2, etc…
var valueToWatch = 'Archive';
var sheetNameToMoveTheRowTo = 'Archive';
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveCell();
if (sheet.getName() == sheetNameToWatch && range.getColumn() == columnNumberToWatch && range.getValue() == valueToWatch) {
var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo);
var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).moveTo(targetRange);
sheet.deleteRow(range.getRow());
}
}
You just need to use copyTo() [1] function instead of moveTo() [2] function which is cutting and pasting the source row. Also, you need to remove the deleteRow function if you just want to leave the row cells with same format and functions set. You only would need to change this:
sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).moveTo(targetRange);
sheet.deleteRow(range.getRow());
To this:
sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).copyTo(targetRange);
Moreover, if you just want to copy the values and not the formulas from the cells to the target sheet, use the copyTo function with options [3], like this:
sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).copyTo(targetRange, SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
[1] https://developers.google.com/apps-script/reference/spreadsheet/range#copytodestination
[2] https://developers.google.com/apps-script/reference/spreadsheet/range#movetotarget
[3] https://developers.google.com/apps-script/reference/spreadsheet/range#copytodestination-copypastetype-transposed
If you want to clear the values without deleting the row, you'll want to change your approach in the following ways:
obtain a Range which includes the data you want to archive
to populate the archive sheet, use copyTo() instead of moveTo()
obtain a Range which includes only the cells you want to clear out
use range.clearContent() to clear that range
Here's a reimplementation of your function. I've extracted the configurable bits into global variables, which makes adjusting them down the line a bit easier to do.
var SOURCE_SHEET_NAME = 'Campaigns';
var TARGET_SHEET_NAME = 'Archive Campaigns';
// The cell value that will trigger the archiving action.
var ARCHIVE_VALUE = 'Archive';
// The column number where you expect the ARCHIVE_VALUE to appear.
var ARCHIVE_COLUMN_NUMBER = 4;
// The starting and ending columns for the range of cells to archive.
var ARCHIVE_START_COLUMN = 1;
var ARCHIVE_END_COLUMN = 15;
// The starting and ending columns for the range of cells to clear.
var CLEAR_START_COLUMN = 1;
var CLEAR_END_COLUMN = 10;
function archiveRow() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var activeCellRange = sheet.getActiveCell();
if (sheet.getName() != SHEET_NAME ||
activeCellRange.getColumn() != ARCHIVE_COLUMN_NUMBER ||
activeCellRange.getValue() != ARCHIVE_VALUE) {
return;
}
var activeCellRow = activeCellRange.getRow();
// Get the range for the data to archive.
var archiveNumColumns = ARCHIVE_END_COLUMN - ARCHIVE_START_COLUMN + 1;
var archiveRowRange = sheet.getRange(activeCellRow, ARCHIVE_START_COLUMN, 1, archiveNumColumns)
// Get the range for the archive destination.
var targetSheet = ss.getSheetByName(TARGET_SHEET_NAME);
var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1, 1, archiveNumColumns);
// Copy the data to the target range.
archiveRowRange.copyTo(targetRange);
// Get the range for the data to clear.
var clearNumColumns = CLEAR_END_COLUMN - CLEAR_START_COLUMN + 1;
var clearRowRange = sheet.getRange(activeCellRow, CLEAR_START_COLUMN, 1, clearNumColumns);
// Clear the row.
clearRowRange.clearContent();
}

Google Script to copy rows to another spread and allow for editing of copy data

I have a form that populates a master spreadsheet, and I have another spreadsheet that gets data from the master sheet. Using the script below I can't edit the information that is copied because whenever the script runs it replaces the edited information to match the master sheet. How can I get the script to only copy data if data hasn't been entered.
ColumnQ's data never changes.
function myFunction() {
var source = SpreadsheetApp.openById('XXX');
var sourcesheet = source.getSheetByName('Lead Sheet');
var target = SpreadsheetApp.openById('XXX')
var targetsheet = target.getSheetByName('Lead Sheet');
var targetrange = targetsheet.getRange(2, 1, sourcesheet.getLastRow(), sourcesheet.getLastColumn());
var rangeValues = sourcesheet.getRange(2, 1, sourcesheet.getLastRow(), sourcesheet.getLastColumn()).getValues();
targetrange.setValues(rangeValues);
}
Do you mean you only want to copy over new rows from the "master" sheet that aren't already in the "target" sheet? If so, assuming column Q is like your "unique key," then you'll have to pull at least this column from each sheet and compare the results. Here's some tested code that does what I believe you want:
function myFunction() {
var qOffset = 16;
var ss = SpreadsheetApp.openById('');
var sourceSheet = ss.getSheetByName('Source');
var targetSheet = ss.getSheetByName('Target');
var sourceValues = sourceSheet.getDataRange().getValues();
var targetValues = targetSheet.getDataRange().getValues();
var deltaValues = [];
for(var i = 0 ; i < sourceValues.length ; i++){
var rowsMatch = false;
for(var j = 0 ; j < targetValues.length ; j++){
if(sourceValues[i][qOffset] == targetValues[j][qOffset]){
rowsMatch = true;
break;
}
}
if(!rowsMatch){
deltaValues.push(sourceValues[i]);
}
}
if(deltaValues.length > 0){
targetSheet.getRange(targetSheet.getLastRow() + 1, 1, deltaValues.length, deltaValues[0].length).setValues(deltaValues);
}
}
Also, I just recently tackled a similar project, but instead of using a "master" sheet, I wrote a function that's triggered by form submissions. When the function is called, it searches my sole spreadsheet for the data; if it finds it, it updates the row, if not, it appends a new row. If that's of any interest to you, I can post parts of the source code.