Google Script: Copy row from one sheet to another depending on value - javascript

While ive seen similar questions ive not seen this specific one if im not mistaken.
So, i need to read all the info in a certain column (in this case it would be AF, regardless i havent been using that spreadsheet to try what ive been doing out) and then check whether a cell in that column has the value(or string, sorry new to Google Script) "Finalized" then copy the entire row that corresponds to that cell to a secondary sheet which would store all the finished cases and stuff.
ive been trying to find something thru google but its always how to copy the entire sheet and thats not useful i think, also what ive done rn copies the cells regardless of what the value is on that cell+column
function copyIf() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getSheetByName("Stuff");
var destination = ss.getSheetByName("Terminados");
var condition = source.getRange('D2:D2000').getValue();
if (condition == "Terminado") {
source.getRange('A2').copyTo(destination.getRange('A2'));
source.getRange('A3').copyTo(destination.getRange('A3'));
}
}
i am thinking i should probably implement some sort of for or while loop cause i want this to run constantly so whenever someone changes the status of a certain cell to Terminado to copy that row to the secondary sheet.

Try this
function copyIf() {
var feuille = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Stuff");
var archive = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Terminados");
if (feuille.getLastRow()==1){
SpreadsheetApp.getActive().toast('No data!', 'End of script šŸ—ƒļø')
return
}
var data = feuille.getRange(2,1,feuille.getLastRow()-1,feuille.getLastColumn()).getValues()
var archiveData = []
var lignes = []
var ligne = 1
var col = 31 // AF
try {
data.forEach(function (row) {
if (row[col]=="Terminado") {
archiveData.push(row)
lignes.push(ligne)
}
})
archive.getRange(archive.getLastRow() + 1, 1, archiveData.length, archiveData[0].length).setValues(archiveData)
// lignes.reverse().forEach(x => feuille.deleteRow(x));
SpreadsheetApp.getActive().toast('Rows '+lignes.flat()+' hab been archived !', 'End of script šŸ—ƒļø')
} catch (e) {
SpreadsheetApp.getActive().toast('No data to be archived!', 'End of script šŸ—ƒļø')
}
}
If you want to delete rows after process, remove // before lignes.reverse().forEach(x => feuille.deleteRow(x));

Related

Script setValue based on the values of column based on value of other column matching reference

https://docs.google.com/spreadsheets/d/1g5mLRcwBb9rLaJ4qIUy1PLaBNNfuwvXwct1cBr2QVgk/edit#gid=1271563337
basicly im trying to figure out a script that would:
Find match in RelaĆ§Ć£o!A:A to content of Config!B3
in my example ABEV3 it would be RelaĆ§Ć£o!A3
that would find a correponding row 3
so the matching cel in RelaĆ§Ć£o!L:L would be RelaĆ§Ć£o!L3
update RelaĆ§Ć£o!L3 with content of Config!D9
basic idea with part of code that i can do to try to ilustrate
function setSheetID()
{
const ss = SpreadsheetApp.getActiveSpreadsheet()
const sheet_c = ss.getSheetByName('Config');
var ticket = ss.getRange(3,2,1,1).getValues(); // Config!B3
var sheetID = ss.getRange(9,4,1,1).getValues(); // Config!D9
const sheet_r = ss.getSheetByName('RelaĆ§Ć£o');
var LR = sheet_r.getLastRow();
var LC = sheet_r.getLastColumn();
var row_to_match_with_ticket = sheet_r.getRange(1,1,LR,1).getValues(); // RelaĆ§Ć£o!A:A
// that part i have no idea how to get range for target where ticket would match with row_to_match_with_ticket, so i will put the result as example
for (var i = 0; i <= 1; i++) // i dont understand that, just setting exemple from posts ive seen
{
if (row_to_match_with_ticket[i] == ticket )
{
var target = sheet_r.getRange(3,12,1,1); // RelaĆ§Ć£o!L3 // im harcoding result, cos i dont fully understant what i wrote in the example
sheet_r.getRange(target).setValues(sheetID);
}
}
};
now i will try to ilustrate with a query: (im not in USA, so ; instead of ,)
to find my target:
query('RelaĆ§Ć£o'!A:L; "SELECT L WHERE (A = '"&Config!B3&"') LIMIT 1";0)
update that cell
UPDATE WITH Config!D9 ( RelaĆ§Ć£o!L:L WHERE RelaĆ§Ć£o!A:A = Config!B3 )
in this case update RelaĆ§Ć£o!L3 WITH VALUES OF Config!D9
searched and results where too complex to me understand and be able to try to adapt to my needs
thanks in advance
Edit: tried to simplify, to make it easier to understand as im terrible to explain aparently, but that script would run on multiple SS that i quite often replace as i improve it, so i need each sheet to update a main sheet
Edit 2: tried to provide a logical way to understant the inputs and outputs, its might be easier to see in the sheet i provided as its comented and colored, tried to describe the best possible way i could
Edit 3: added basic code to try to show what i want to do
I believe your goal is as follows.
You want to retrieve the value of cell "B3" of "Config" sheet.
You want to search the retrieved value from the column "A" of "RelaĆ§Ć£o" sheet.
When the value is found, you want to put the value of cell "D9" of "Config" sheet to the column "L" of the same row of the searched value.
In this case, how about the following sample script?
Sample script:
function myFunction() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const [src, dst] = ["Config", "RelaĆ§Ć£o"].map(s => ss.getSheetByName(s));
const [b3, d9] = ["B3", "D9"].map(r => src.getRange(r).getValue());
const search = dst.getRange("A2:A" + dst.getLastRow()).createTextFinder(b3).findNext();
if (!search) return;
search.offset(0, 11).setValue(d9);
}
In this answer, the value is searched using TextFinder.
Reference:
createTextFinder(findText)

Google Script return value from one sheet to another sheet

This is my first Google Script and I'm struggling a little bit while trying to bring back the values from a specific cell & sheet to another sheet.
I have a total of 18 columns, being the first one the ID which is going to be the input that the user would need to add in order to retrieve the data from one sheet to another. As the first one is the ID, and will be already be inputted by the user, I would need to retrieve the data from columns 2 to 18
Here is my code:
function SearchID() {
var columnIndex = 0;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formS = ss.getSheetByName("Manual Costs App"); // App sheet
var str = formS.getRange("D6").getValue(); // The ID to search will be inputted here
var dataS = ss.getSheetByName("Inputs").getDataRange().getValues(); // Retrieving the data based on the user input
for (var i = 0; i<=dataS.length; i++) {
var row = dataS[i];
if (row[columnIndex] == str) {
formS.getRange("D9").setValue(row[1]);
formS.getRange("D13").setValue(row[2]);
formS.getRange("D14").setValue(row[3]);
formS.getRange("D15").setValue(row[4]);
formS.getRange("D16").setValue(row[5]);
formS.getRange("D18").setValue(row[6]);
formS.getRange("D19").setValue(row[7]);
formS.getRange("D20").setValue(row[8]);
formS.getRange("D21").setValue(row[9]);
formS.getRange("D22").setValue(row[10]);
formS.getRange("D23").setValue(row[11]);
formS.getRange("D25").setValue(row[12]);
formS.getRange("D26").setValue(row[13]);
formS.getRange("D27").setValue(row[14]);
formS.getRange("D28").setValue(row[15]);
formS.getRange("D29").setValue(row[16]);
formS.getRange("D30").setValue(row[17]);
break;
}
}
}
The link to a sample spreadsheet of what I'm building is here
Update: Everything is fixed now! What I did was removing the space in the for loop. After that, it retrieved the data but a TypeError: Cannot read property '0'. Also solved it adding a break after the loop to avoid it.
It's a type in your for loop, notice how spelled length:
for (var i = 1; i <= values.lenght; i++)
You also don't want to set values line by line like you do, get a longer range and set the values with setValues() rather than setValue(). There's quite a bit of refactoring to do there actually.
The user did found the answer and updated it on the question.
Posting here as community wiki so it can be seen more clearly.
User's answer:
Update: Everything is fixed now! What I did was removing the space in the for loop. After that, it retrieved the data but a TypeError: Cannot read property '0'. Also solved it adding a break after the loop to avoid it.
function SearchID() {
var columnIndex = 0;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formS = ss.getSheetByName("Manual Costs App"); // App sheet
var str = formS.getRange("D6").getValue(); // The ID to search will be inputted here
var dataS = ss.getSheetByName("Inputs").getDataRange().getValues(); // Retrieving the data based on the user input
for (var i = 0; i<=dataS.length; i++) {
var row = dataS[i];
if (row[columnIndex] == str) {
formS.getRange("D9").setValue(row[1]);
formS.getRange("D13").setValue(row[2]);
formS.getRange("D14").setValue(row[3]);
formS.getRange("D15").setValue(row[4]);
formS.getRange("D16").setValue(row[5]);
formS.getRange("D18").setValue(row[6]);
formS.getRange("D19").setValue(row[7]);
formS.getRange("D20").setValue(row[8]);
formS.getRange("D21").setValue(row[9]);
formS.getRange("D22").setValue(row[10]);
formS.getRange("D23").setValue(row[11]);
formS.getRange("D25").setValue(row[12]);
formS.getRange("D26").setValue(row[13]);
formS.getRange("D27").setValue(row[14]);
formS.getRange("D28").setValue(row[15]);
formS.getRange("D29").setValue(row[16]);
formS.getRange("D30").setValue(row[17]);
break;
}
}
}

Google Sheets, For Loop to auto update stocks from google api

As the title describes I'm trying to update a stock price with a script. I understand that this is likely trivial for most of you, but it's my first time scripting with google sheets.
From what I can see this code should be okay and the code within the loop does work on it's own.
It makes a list for for every time the list has a value it will process the command. Currently the command will only repeat on the same row as I've not figured how to increment the row properly yet.
I want to read from column A and as long as there is a value to increment which A row is read to get the stock symbol, pull the value, and paste it in an incremented E row.
function getData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var symbol = ss.getRange("A2:A").getValues();
for (var row = 2, var count = symbol.length; row < count; row++) {
if (symbol[row] !=''){
ss.getRange('E2').setValue('=GOOGLEFINANCE(A2)');
}
}
}
I think this will get you what you want. The issue with your script was that the E2 was hardcoded in, as was the A2 so it didn't iterate through as needed.
function getData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var symbol = sheet.getRange("A2:A").getValues();
for(i=0; i<symbol.length; i++)
{
if (symbol[i]!=""){
ss.getRange('E'+(i+2)).setValue('=GOOGLEFINANCE(A'+(i+2)+')');
}
}
}

Updating a sheet with a value if strings match on two sheets

Sheet 2 has all the items and their statuses, while Sheet 1 has only some of the items from Sheet 2. I want to be able to see every time an item mentioned on Sheet 1 is listed as having a status update, i.e. e date, on Sheet 2.
Here's what I have so far, but having trouble calling the right range to work with. Is there a simpler way to do what I want to do?
function statusupdate() {
var activesht = SpreadsheetApp.getActiveSpreadsheet();
var statussht = activesht.getSheetByName("Sheet 2"); //get sheet on which status update occurs
var statusrng1 = statussht.getRangeByName('B');
var statusrng2 = statussht.getRangeByName('C');
var mainsht = activesht.getSheetByName("Sheet 1"); //get sheet where you show a specific thing has been updated, if that thing mentioned here.
var mainrng = mainsht.getRangeByName('F');
if (statusrng1 == mainrng) {
var date = statusrng2.getValue();
var daterng = mainrng.getRangeByName('E');
daterng.setValues(date);
}
}
Spreadsheet formula
You can have the rows in one sheet follow those in another without using a script. For example, say we have a sheet named Items that contains one row for every item we carry, with the item number in the first column.
We can use VLOOKUP() to search for the row containing info about individual items, and select specific columns from it.
For example, this formula would be used in B2, and could be copied to other cells in our sheet:
=VLOOKUP($A2,Items!$A$2:$C$7,COLUMN(),false)
Script
There are a few issues with your script.
.getRangeByName('B') - This method gets a named range. Given the name, I suspect you mean to get column B, and NOT a named range. If that's the case, you could use this instead:
var statusrng1 = statussht.getRange('B:B');
In A1Notation, the range B:B is the entire column B.
You intend to copy values, so there is another step required beyond identifying ranges; you need to first read the values from a range, and then later write them to a different range. For that, you need to use methods like getValues() and setValues().
Here's an updated version of your script, adapted to the example spreadsheet described above.
function statusupdate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
//get sheet on which status update occurs
var statusSheet = ss.getSheetByName("Items");
var statusRange = statusSheet.getDataRange();
var statusData = statusRange.getValues();
//get sheet where you show a specific thing has been updated, if that thing mentioned here.
var trackingSheet = ss.getSheetByName("Tracking");
var trackingRange = trackingSheet.getDataRange();
var trackingData = trackingRange.getValues();
// Loop over all rows in the Tracking sheet to update from the Items sheet
// Start with row=1, because row 0 contains headers
for (var row=1; row<trackingData.length; row++) {
var item = trackingData[row][0];
if (item == '') continue; // skip rows without item #
// Look for item in Items sheet
var statusRow = null;
for (var sRow=1; sRow<statusData.length; sRow++) {
if (statusData[sRow][0] == item) {
// Found our match, grab that row
statusRow = statusData[sRow];
break;
}
}
// If we found a matching row, copy the status
if (statusRow) {
// Customize this depending on how your sheets are organized
trackingData[row][1] = statusRow[1];
trackingData[row][2] = statusRow[2];
}
}
// All values have been copied to trackingData, now write to sheet
trackingRange.setValues(trackingData);
}

Google Script: Format URL in Array.Push

I have a working script that upon form submit, specific rows move from one sheet to another. One of the fields I'm pushing is a url.
On the second sheet, the link is listed and it is hyperlinked, but it's really ugly and I really want to format it so that it shows "Edit" with a hyperlink. I've tried a number of ways, but my knowledge is limited so all I get are errors. I'm hoping someone can point me in the right direction.
Here is my code. I'm very new at this so the script is not at all sophisticated. Any help/suggestions would be appreciated!
function copyAdHoc(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = SpreadsheetApp.setActiveSheet(ss.getSheetByName("Form Responses 1"));
var data = sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
// Grab the Headers from master sheet
var headers = sh.getRange(1,1,1,sh.getLastColumn()).getValues();
var date = headers[0].indexOf('Effective Date');
var name = headers[0].indexOf('Employee Name');
var loc = headers[0].indexOf('Location');
var issue = headers[0].indexOf('Description/Question/Issue');
var add = headers[0].indexOf('Additional Information');
var change = headers[0].indexOf('Is this a Qualifying Life Event?');
var url = headers[0].indexOf('Form URL');
var category = headers[0].indexOf('Primary Category');
var status = headers[0].indexOf('Current Status');
var users = headers[0].indexOf('Users');
// Grab only the relevant columns
for(n = 0; n < data.length; ++n ) { // iterate in the array, row by row
if (data[n][change] !== "Yes" & data[n][category] !== "Employee Relations" & data[n][date] !== "") { // if condition is true copy the whole row to target
var arr = [];
arr.push(data[n][url]);
arr.push(data[n][users]);
arr.push(data[n][date]);
arr.push(data[n][loc]);
arr.push(data[n][name]);
arr.push(data[n][category]);
arr.push(data[n][issue] + ". " + data[n][add]);
arr.push(data[n][status]);
var sh2 = SpreadsheetApp.setActiveSheet(ss.getSheetByName("Ad Hoc")); //second sheet of your spreadsheet
sh2.getRange(sh2.getLastRow()+1,2,1,arr.length).setValues([arr]); // paste the selected values in the 2cond sheet in one batch write
}
}
}
It's a bit messy but the only way I know to achieve what you're trying to do would be to insert a column to the left of the hyperlink with the word Edit right justified and then remove the borders between the two.
From your description I am assuming you want the word "Edit" to be Hyperlinked. To do so, try this:
function getHyperlink(url)
{
return "=HYPERLINK(\""+url+"\","+"\"Edit\""+")";
}
function mainFunct()
{
//Do necessary steps
var tarLink = "https://www.google.com";
var tarRng = tarSheet.getRange(rowNum, colNum).setValue(getHyperlink(tarLink));
//perform other steps
}
EDIT:
Forgot to mention, since you're pushing your values to the array... you can do it in a similar way by either just storing the hyperlink in a variable or directly pushing it to the array like all the other values. Or if you're dealing with a hyperlink that has a static and dynamic part, For example: https://stackoverflow.com/questions/post_id, where post_id keeps changing but most of the URL is static, you can easily handle it by just passing the post_id to the getHyperlink function and getting the required Hyperlink in return. Hope this helps.

Categories