Add date and text at the last row after a copy paste - google-apps-script

I'm breaking my head here trying to figure it out a way to achieve this in a simples way.
I got working a code that copies a range from a sheet and paste in another at the last row.
function copyInfo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ss.getSheetByName("Review");
var pasteSheet = ss.getSheetByName("Log");
// get source range
var source = copySheet.getRange(3,2,15,5);
// get destination range
var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,3,15,5);
// copy values to destination range
source.copyTo(destination, SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}
The problem is, at the destination sheet, I still have columns A and B empty. By each row in the source (varies from time to time) copied, I need to place at column A todays date and column B the text "Review".
Like: Date (column A) | Revview (column B) | Pasted Data from Source (column C and other)
Do I need to write a completely new code to check for empty or can I implement both solutions into this code?

The code should fill the two cells before your data. It also caters for the setup where you have three areas in the same sheet.
Each copyInfoXd_button function will be assigned to your button image.
function copyInfo1d_button() {
copyInfo(2, "B1:B");
}
function copyInfo7d_button() {
copyInfo(9, "I1:I");
}
function copyInfo30d_button() {
copyInfo(16, "P1:P");
}
function copyInfo(startingCol, subjectCol)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ss.getSheetByName("Review");
var pasteSheet = ss.getSheetByName("Log");
const sourceCols = 4; //actual number of columns to copy, not including the empty column H
const destCols = 6; //actual number of columns to write to, from DATE to OBS
//find the last row from a colum
var avals = copySheet.getRange(subjectCol).getValues();
var lastRow = avals.filter(String).length;
var rowsToCopy = lastRow - 2; //skip the first 2 rows as they are headers
// get source range
var source = copySheet.getRange(3,startingCol,rowsToCopy,sourceCols); // row, column, number of rows and number of columns
// get destination range
var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,1,rowsToCopy,destCols);
var data = [];
var sourceValues = source.getValues();
//construct new data for the destination range
for (var row in sourceValues) {
var destRow = [Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone(), 'MMMM dd, yyyy'), 'Review'];
destRow = destRow.concat(sourceValues[row]);
data.push(destRow);
}
destination.setValues(data);
}

I made it! I'm so proud! Thank you all for the help!
I'm beginning to do stuff like this!
After the Charles answer I looked for a way to add to each row. However, I know the code might not be too elegant, and I couldn't figured it out a way of doing using script itself, so I added a helper cell inside the sheet in H1 and H2.
Here's the solution:
function copyInfo24() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ss.getSheetByName("Review");
var pasteSheet = ss.getSheetByName("Log");
// get source range
var source = copySheet.getRange(4,2,99,5);
// get destination range
var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,3,99,5);
// copy values to destination range
source.copyTo(destination, SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
// Sets date at Column A and "Review" at Column B.
var data = [];
for(var i =0; i < copySheet.getRange("H1").getValue(); i++) {
data.push([Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone(), 'MMMM dd, yyyy'), 'Review']);
}
reviewRange = pasteSheet.getRange(pasteSheet.getLastRow()-copySheet.getRange("H2").getValue(), 1, copySheet.getRange("H1").getValue(), 2)
reviewRange.setValues(data); //set the date and 'Review' data
}

Related

Getting Specific Rows from Another Google Sheet via App Script Based on Multiple Cell Values

I would like to fetch data from another google sheet, then retrieve all columns(been successful with this one). As for the rows, I would only like to retrieve all rows with these values, "Mrm1, Mrm2, Mrm3" from Measurement Column.
For example, I have these on another sheet,Original Data
And on another sheet, I want the result to be like this: Expected Retrieved Data
So far, I have this, but I'm not sure how to apply what I need on the rows. This script is retrieving everything.
function Country A() {
var sss = SpreadsheetApp.openById("19-idD8PWuNxnvzRVqBlKhju2RkKxOe8nUQaf9ZMAcgk"); // Source spreadsheet - replace with actual key
var ss = sss.getSheetByName('Compiled'); // Source sheet - change to actual name
var numRows = ss.getLastRow() // get last row with data
var numColumn = ss.getLastColumn(); // get last column with data
var srange = ss.getRange(2,1,numRows,numColumn); // Source range - change to actual range
var values = srange.getDisplayValues();
var lss = SpreadsheetApp.getActiveSpreadsheet(); // Local spreadsheet - the one this script is in
var targetnumRows = lss.getSheetByName('Country A').getMaxRows();
var targetnumcolumns = lss.getSheetByName('Country A').getMaxColumns();
var ls = lss.getSheetByName('Country A').getRange(2,1,numRows,numColumn); // Local sheet - change to actual name and Local range - change to actual range
var TargetRange = lss.getSheetByName('Country A').getRange(2,1,targetnumRows,targetnumcolumns); // Local sheet - change to actual name and Local range - change to actual range
TargetRange.clear() //Clear Sheet Content
ls.setValues(values); // Copy from source sheet to local sheet
var sheet = lss.getSheetByName('Country A');
var maxColumns = sheet.getMaxColumns();
var lastColumn = sheet.getLastColumn();
var maxRows = sheet.getMaxRows();
var lastRow = sheet.getLastRow();
if (maxColumns-lastColumn != 0){sheet.deleteColumns(lastColumn+1, maxColumns-lastColumn)};
if (maxRows-lastRow != 0){sheet.deleteRows(lastRow+1, maxRows-lastRow)};
var TargetHour = lss.getSheetByName('Country A').getRange(1,1).setValue(Utilities.formatDate(new Date(), "CST", "MM-dd-yyyy HH:mm:ss"));
}
Please help me. Thank you.
The script stores the values in a 2D array. You have to iterate through the elements and delete the elements where column E (Col number 4) (A=0, B=1,...E=4) is not equal to "Mrm1, Mrm2, Mrm3".
Then you paste the modified array in the second sheet.
Here is an example. You need to adapt it to your code.
function copyData() {
var ss = SpreadsheetApp.openById("YOUR-ID");
// Stores data as a 2D Array
var data = ss.getSheetByName("Sheet1").getRange("A1:M10").getValues();
// Remove rows where column E not equals "Mrm1, Mrm2, Mrm3"
for (var i = 0; i < data.length; i++) {
if (data[i][4] !== "Mrm1" && data[i][4] !== "Mrm2" && data[i][4] !== "Mrm3") {
data.splice(i,1);
i--;
}
}
// Paste data in sheet 2
var pasteRange = "A1:M" + (data.length);
ss.getSheetByName("Sheet2").getRange(pasteRange).setValues(data);
}

Google Script: copy values from one sheet to another determining the range

I have two sheets with unique IDs in one column. I need to make sure whenever a new ID is added in one sheet (Sheet1), it is copied to the last empty row in the other sheet (Sheet2). The IMPORTRANGE won't work as being dynamic any static information added in the other sheet would be irrelevant to the respective ID.
In another thread [1], I got help developing this script that will do exactly that. However, this script will insert the data in the other sheet in Column A. How can I modify the script so I can decide the specific range where I want the script to insert the data (in Sheet 2).
Update: I created this spreadsheet as an example. I'm trying to ensure that the script does the calculation (ie. adding vlaues that are not duplicated in the first available empty row), starting in cel C10 in "Sheet2". It would be also great if I can somehow change that range if I need to: https://docs.google.com/spreadsheets/d/1abESAXFrOHoqRQRNqQGfmAFxlbD10wlprAf1tca4y7o/edit#gid=132361488
Thanks!
function updateSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = "Sheet1";
var destinationSheet = "Sheet2";
var source_sheet = ss.getSheetByName(sourceSheet);
var target_sheet = ss.getSheetByName(destinationSheet);
var lastCol = target_sheet.getLastColumn();
var lastRow = target_sheet.getLastRow();
if (lastRow > 1) { // <--- Added
var r = target_sheet.getRange(2,1, lastRow - 1, lastCol);
r.sort([{column: 1, ascending: true}]);
}
_updateSpreadsheet(source_sheet, target_sheet);
}
function _updateSpreadsheet(source_sheet, target_sheet) {
var last_row = target_sheet.getLastRow();
var source_data = source_sheet.getRange("A4:A" + source_sheet.getLastRow()).getValues(); // <--- Modified
var target_data = target_sheet.getDataRange().getValues();
var resultArray = [];
for (var n = 0 ; n < source_data.length ; n++) { // <--- Modified
var keep = true;
for(var p in target_data) {
if (source_data[n][0] == target_data[p][0]) {
keep = false; break;
}
}
var columnsToKeep = [0];
var tempData = [];
if(keep){
for(var c in columnsToKeep){ tempData.push(source_data[n][columnsToKeep[c]])}
resultArray.push(tempData);
}
}
last_row++;
resultArray = resultArray.filter(String); // <--- Added
if(resultArray.length>0){
target_sheet.getRange(last_row,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
}
[1] Google Script: Append new values in column to another sheet
target_sheet.getRange(last_row,1,resultArray.length,resultArray[0].length)
.setValues(resultArray);
This line
Takes the sheet stored in the variable target_sheet
Accesses the defined range
Sets values
The syntax to access a range used in your code is getRange(row, column, numRows, numColumns)
whereby the start column is numerical - in your case it's 1 which corresponds to column A.
If you want to modify the start column from A to B:
Just change your range definition from
getRange(last_row,1,resultArray.length,resultArray[0].length)
to
getRange(last_row,2,resultArray.length,resultArray[0].length)

Google Apps Script - Copy rows from one sheet containing today's date into another

What I'm trying to do is within one spreadsheet, look at sheet "Source", if a cell in column B contains today's date, then copy cells between A:B for that cell and paste onto next empty row in sheet "Destination".
Repeat for all cells containing today's date.
This works if I'm looking for a text but essentially I'm trying to make this run automatically everyday when the date changes and I can't get the date function to work properly.
Essentially at the turn of each day it would copy today's data from another automated sheet, and paste it in the next row down from yesterday's data in another sheet.
I'm quite new to all of this and any help would be greatly appreciated.
function copy_test() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Source"); //Source sheet
var ds = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Destination"); //Destination sheet
var testrange = ss.getRange('B:B'); //Column to check for today's date
var testvalue = (testrange.getValues()); //What value to check
var today = Utilities.formatDate(new Date(), 'GMT-0', 'dd/MM/yyyy');
var data = [];
var j = [];
//Condition to check in B:B, if true, copy the same row to data array
for (i=0;i<testvalue.length;i++) {
if (testvalue[i] == today) {
data.push.apply(data,ss.getRange(i+1,1,1,3).getValues());
//Copy matched ROW numbers to j
j.push(i);
}
}
//Copy data array to destination sheet
ds.getRange(ds.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}
The error I get is:
TypeError: Cannot read property "length" from undefined. (line 20, file "First Test")
Picture of the type of data I want to copy
Try this:
function copy_test() {
var ss=SpreadsheetApp.getActive();
var ssh=ss.getSheetByName("Source");
var dsh=ss.getSheetByName("Destination");
var rg=ssh.getRange(1,1,ssh.getLastRow(),3);//I just took the first three columns instead
var vA=rg.getValues();
var dt=new Date();
var today=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();//midnight
for(var i=0;i<vA.length;i++) {
var d=new Date(vA[i][1]);//column B
if (new Date(d.getFullYear(),d.getMonth(),d.getDate()).valueOf() == today) {
dsh.appendRow(vA[i]);
}
}
}
In case anyone comes across this problem in the future. I messed around with the original code some more and managed to get it to work:
function copyrange() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Source'); //source sheet
var testrange = sheet.getRange('B:B');
var testvalue = (testrange.setNumberFormat("#").getValues());
var ds = ss.getSheetByName('Destination'); //destination sheet
var data = [];
var j =[];
var dt = new Date();
var today = Utilities.formatDate(new Date(), 'GMT-0', 'dd/MM/yyyy')
//Condition to check in B:B, if true, copy the same row to data array
for (i=0;i<testvalue.length;i++) {
if (testvalue[i] == today) {
data.push.apply(data,sheet.getRange(i+1,1,1,3).getValues());
//Copy matched ROW numbers to j
j.push(i);
}
}
//Copy data array to destination sheet
ds.getRange(ds.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}
Specifically var testvalue where I added in setNumberFormat for the dates as text because that's the only way it would work for if (testvalue[i] == today)
Thanks #Cooper for taking a shot at this.

Move Rows En Masse Contingent on Value in One Column

I have a script setup that moves all the records in a sheet into another sheet. However, I would like to add functionality to only move records that have the value "Approved" in a specific column (column I for my current situation). I've seen some other questions/answers to move individual rows based on values, but I haven't figured out how to leverage these scripts to run across a full spreadsheet. My guess is I can use a for loop but how?
Current script:
function MoveRecords(){
//Original Sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Example Input")
//Calculate # of Rows Ignoring Blank Array Values
var Rows = ss.getRange("A2:A").getValues();
var NumRows = Rows.filter(String).length;
/*Add a For Loop here to only get the rows with Approved in Column I?*/
//Parsed Data to Move
var rangeValues1 = sheet.getRange(2,1,NumRows,1).getValue();
var rangeValues2 = sheet.getRange(2,2,NumRows,5).getValues();
//Destination of Parsed Data
var DestinationSS = SpreadsheetApp.openById('ID');
var DestinationSheet = DestinationSS.getSheetByName('Approved');
var DestinationLastRow = DestinationSheet.getLastRow()+1;
//Move the Data
DestinationSheet.getRange(DestinationLastRow,3,NumRows,1).setValue(rangeValues1);
DestinationSheet.getRange(DestinationLastRow,5,NumRows,5).setValues(rangeValues2);
};
Any help is greatly appreciated!
You can get all values, filter every row for Approved then write those rows into destination sheet.
function MoveRecords() {
//Original Sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Example Input');
var values = sheet.getDataRange().getValues();
/*Add a For Loop here to only get the rows with Approved in Column I?*/
// col I = index 8
var res = values.filter(function(row) {
return row[8] == 'Approved';
});
//Parse Data to Move
var rangeValues1 = res.map(function(row) {
return [row[0]];
});
var rangeValues2 = res.map(function(row) {
row.shift();
while (row.length > 5) row.pop();
return row;
});
//Destination
var DestinationSS = SpreadsheetApp.openById('ID');
var DestinationSheet = DestinationSS.getSheetByName('Approved');
var DestinationLastRow = DestinationSheet.getLastRow() + 1;
//Move the Data
DestinationSheet.getRange(DestinationLastRow, 3, rangeValues1.length, 1).setValues(rangeValues1);
DestinationSheet.getRange(DestinationLastRow, 5, rangeValues2.length, 5).setValues(rangeValues2);
}

What's the most efficient way to copy a column of cells from one spreadsheet to another?

I am trying to copy one column of cells from a spreadsheet to another (append it at the bottom). The code below works, but I was wondering if it's possible to do this without a loop. Is there a faster or more efficient way of doing this?
function CopyToAnotherSheet() {
var sourceSpreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sourceSpreadSheet.getSheets()[0];
var destinationSpreadSheet = SpreadsheetApp.openById('15-vXNpnzSEKzcqhBmJ_D173rwGyM7TOAZE1iL_wsf2A');
var destSheet = destinationSpreadSheet.getSheets()[0];
// Get the contents of a cell in srcSheet
var range = srcSheet.getRange("xposed!A1:A")
var values = range.getValues();
for (var i = 0; i < values.length; i++) {
destSheet.appendRow(values[i]);
}
}
Cheers!
you can use the getRange() method with setValues to setValues() to set the range as the array only.
Refer this documentation for getting a clear idea Document Link
function CopyToAnotherSheet() {
var sourceSpreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sourceSpreadSheet.getSheets()[0];
var destinationSpreadSheet = SpreadsheetApp.openById('15-vXNpnzSEKzcqhBmJ_D173rwGyM7TOAZE1iL_wsf2A');
var destSheet = destinationSpreadSheet.getSheets()[0];
// Get the contents of a cell in srcSheet
var range = srcSheet.getRange("xposed!A1:A")
var values = range.getValues();
//returns last row of the destination sheet
var lastRow=destSheet.getLastRow();
//starting from the last row, it will apend the array in the column
//getrange(num of row to start from, num of column to start from, number of rows in array to append, num of column in array to append)
destSheet.getRange(lastRow+1, 1, values.length,1).setValues(values);
}