I have a destination sheet where in Col "B" there are a list of "Companies", in Col "K" I would to choose, with a dropdown, the "Address" available (of that specific "Company") taken from another sheet, located in col B and J.
How to do this with a script?
https://docs.google.com/spreadsheets/d/15g_3TMmVufKZogCbO3SUWBUp3iwc21nQgPBw6_GWXQQ/edit
I believe your goal as follows.
You want to put the data validation rules to the column "K2:K" in the sheet destination.
You want to create the rules by retrieving the values from the columns "B" and "J" in the sheet source.
For this, how about this answer?
Flow:
Retrieve values from the both sheets.
Create an object for creating the rules.
Create the rules.
Put the rules to the column "K" in the sheet destination.
Sample script:
function myFunction() {
// 1. Retrieve values from the both sheets.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const src = ss.getSheetByName("source");
const dst = ss.getSheetByName("destination");
const srcValues = src.getRange("A2:J" + src.getLastRow()).getValues();
const dstValues = dst.getRange("B2:B" + dst.getLastRow()).getValues();
// 2. Create an object for creating the rules.
const obj = srcValues.reduce((o, [a,b,,,,,,,,j]) => Object.assign(o, {[a]: [b, j]}), {});
// 3. Create the rules.
const rules = dstValues.map(([e]) => ([SpreadsheetApp.newDataValidation().requireValueInList(obj[e]).build()]));
// 4. Put the rules to the column "K" in the sheet `destination`.
dst.getRange("K2:K" + dst.getLastRow()).setDataValidations(rules);
}
References:
newDataValidation()
setDataValidations()
Added 1:
For your 3 additional questions in your replying, I answer as follows.
Q1: If in future I would to retrieve the values from further columns in the sheet source. How to edit the script?
A1: In this case, please modify [a,b,,,,,,,,j]. Now, a, b and j are Company, Address options 1 and Address options 2, respectively.
Q2: To have the sheets update with the script, you suggest me to activate a trigger?
A2. I cannot understand what you want to do.
Q3: If I put a value in the col "B" (destination) that is not present in col "A" (source), the script not works. I need this.
A3: Please modify above script as follows.
From
- const rules = dstValues.map(([e]) => ([SpreadsheetApp.newDataValidation().requireValueInList(obj[e]).build()]));
To
const rules = dstValues.map(([e]) => ([obj[e] ? SpreadsheetApp.newDataValidation().requireValueInList(obj[e]).build() : null]));
Added 2:
The question 2, I explain. Naturally when I run the script the dropdown are populated, but if I add a new company, I must to run again the script and so on... to avoid this, how can I do?
For above your additional 2nd question, the sample script is as follows. In this case, when the column "B" of the sheet of destination is edited, the script is run. In this case, the simple trigger can be used.
Sample script:
function onEdit(e) {
const range = e.range;
const sheet = range.getSheet();
if (range.getColumn() != 2 || sheet.getSheetName() != "destination") return;
// 1. Retrieve values from the both sheets.
const ss = e.source;
const src = ss.getSheetByName("source");
const dst = ss.getSheetByName("destination");
const srcValues = src.getRange("A2:J" + src.getLastRow()).getValues();
const dstValues = dst.getRange("B2:B" + dst.getLastRow()).getValues();
// 2. Create an object for creating the rules.
const obj = srcValues.reduce((o, [a,b,,,,,,,,j]) => Object.assign(o, {[a]: [b, j]}), {});
// 3. Create the rules.
const rules = dstValues.map(([e]) => ([obj[e] ? SpreadsheetApp.newDataValidation().requireValueInList(obj[e]).build() : null]));
// 4. Put the rules to the column "K" in the sheet `destination`.
dst.getRange("K2:K" + dst.getLastRow()).setDataValidations(rules);
}
Related
I have a column with strings containing a name and an ID concatenated. How can I extract just the name part of the string and use that for filtering a dataset and copying it over to another worksheet in the google sheets file using the google apps script? The main thing I'm having difficulty with is just extracting the names from the column since they can vary in length. Additionally, I'm trying to perform automation using google apps script, so I want to avoid making a column manually and use something like regex.
Below is an example of how the column values look:
Identity
Jane100
Adam500
Adam500
Erica234
Jessica8
We can use regular expressions here:
var input = "Adam500";
var regExp = new RegExp("([a-z]+)", "i")
var name = regExp.exec(input)[1];
Logger.log(name); // Adam
I believe your goal is as follows.
You want to copy the following values on a column of the source sheet.
Identity
Jane100
Adam500
Adam500
Erica234
Jessica8
And, you want to paste the following values to a column of the destination sheet (in the same Spreadsheet) by converting from the above values.
Identity
Jane
Adam
Adam
Erica
Jessica
You want to achieve this using Google Apps Script.
In this case, how about the following sample script?
Sample script 1:
function sample1() {
const srcSheetName = "Sheet1"; // Please set the source sheet name.
const dstSheetName = "Sheet2"; // Please set the destination sheet name.
const srcColumn = 1; // Values are retrieved from column "A".
const dstColumn = 1; // Values are put to the column "A".
const ss = SpreadsheetApp.getActiveSpreadsheet();
const [srcSheet, dstSheet] = [srcSheetName, dstSheetName].map(e => ss.getSheetByName(e));
const srcValues = srcSheet.getRange(1, srcColumn, srcSheet.getLastRow()).getValues();
const dstValues = srcValues.map(([a], i) => [i == 0 || !a.toString() ? a : a.replace(/\d+/g, "")]);
dstSheet.getRange(1, dstColumn, dstValues.length).setValues(dstValues);
}
In this sample script, the values are retrieved from the column of the source sheet, and the converted values are put on the destination sheet.
Sample script 2:
function sample2() {
const srcSheetName = "Sheet1"; // Please set the source sheet name.
const dstSheetName = "Sheet2"; // Please set the destination sheet name.
const srcColumn = 1; // Values are retrieved from column "A".
const dstColumn = 1; // Values are put to the column "A".
const ss = SpreadsheetApp.getActiveSpreadsheet();
const [srcSheet, dstSheet] = [srcSheetName, dstSheetName].map(e => ss.getSheetByName(e));
const last = srcSheet.getLastRow();
const dstRange = dstSheet.getRange(1, dstColumn);
srcSheet.getRange(1, srcColumn, last).copyTo(dstRange);
dstRange.offset(1, 0, last - 1).createTextFinder("\\d+").useRegularExpression(true).replaceAllWith("");
}
In this sample script, the values are copied from the column of the source sheet to the destination sheet. And, the copied values are converted. In this case, the text styles can be copied.
References:
getValues()
setValues(values)
createTextFinder(findText)
SpreadsheetApp how to return unique values from an array
in this post how to count a duplicate values and show theme in sheetname('test2') Range ('B2:B7')
here my google sheet https://docs.google.com/spreadsheets/d/1HN0XCLrEzlRkInIv6xFnhCFnhZabu7Y-Tz1dvYvsGQM/edit?usp=sharing
In your situation, how about the following sample script?
Sample script:
function myFunction() {
const srcSheetName = "test"; // Please set the source sheet name.
const dstSheetName = "test2"; // Please set the destination sheet name.
// Retrieve source and destination sheets.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const [srcSheet, dstSheet] = [srcSheetName, dstSheetName].map(s => ss.getSheetByName(s));
// Retrieve source values and create an object for putting to the destination sheet.
const srcValues = srcSheet.getRange("A2:A" + srcSheet.getLastRow()).getValues();
const obj = srcValues.reduce((o, [a]) => (o[a] = o[a] ? o[a] + 1 : 1, o), {});
// Retrieve the values of column "A" from the destination sheet and create an array for putting to Spreadsheet.
const dstRange = dstSheet.getRange("A2:A" + dstSheet.getLastRow());
const dstValues = dstRange.getDisplayValues().map(([a]) => [obj[a] || 0]);
// Put the result values to the column "B" of the destination sheet.
dstRange.offset(0, 1).setValues(dstValues);
}
From your provided Spreadsheet, the sample sheet names are test and test2. Please modify this for your actual situation.
When you run this script, the values are retrieved from the source sheet and the count of each value is calculated. And, the result values are put to the column "B" of the destination sheet.
Note:
This sample script is for your provided Spreadsheet. When you change the structure of the Spreadsheet, this script might not be able to be used. Please be careful about this.
References:
reduce()
map()
I'm looking to get some help with Google Docs and Scripts. I have a workflow list that shows names of employees assigned to a task. There is also another field that indicates employees off of the day. I would like a script that can be run that would strikethrough the names of the individuals identified as off for the day. There could be multiple individuals off, so it would need to include a series of cells to reference. Results to look something like this.
[Requested outcome1
The problem I am running into is I cannot successfully find any code for even a starting point. I have seen pieces here and there, but nothing that is complete enough for me to even determine a starting point. I'm reasonably technical, but am not familiar with script writing. I have been unable to find a decent writeup on something like this so am requesting assistance if possible. Thank you!
Here is the code attempted where I am getting illegal argument on Line 27 currently. I will have it linked to a button. The individual in charge of updating the sheet daily will make all the daily changes, then once done click to button to clear any strikethrough and initiate based on new names input, if there are any.
Sample sheet link here.
https://docs.google.com/spreadsheets/d/1chSTd7Zy1qqu32qu4spSJJanwTI1SnH6rJtoMxb7iEc/edit?usp=sharing
function myFunction()
{
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('B:B').activate();
spreadsheet.getActiveRangeList().setFontLine(null);
const sheetName = "Sheet1"; // Please set the sheet name.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const range = sheet.getRange('B2:B')
const textsForStrikethrough = sheet.getRange("A15:A20").getValues().flat(); // Added
const modify = range.getValues().reduce((ar, e, r) => {
e.forEach((f, c) => {
textsForStrikethrough.forEach(g => {
const idx = f.indexOf(g);
if (idx > -1) ar.push({start: idx, end: idx + g.length, row: r, col: c});
});
});
return ar;
}, []);
const textStyle = SpreadsheetApp.newTextStyle().setStrikethrough(true).build();
const richTextValues = range.getRichTextValues();
modify.forEach(({start, end, row, col}) => richTextValues[row][col] = richTextValues[row][col].copy().setTextStyle(start, end, textStyle).build());
range.setRichTextValues(richTextValues);
}
I believe your goal as follows.
You want to reflect the strikethrough to the partial text in a cell using Google Apps Script as follows. (The sample image is from your question.)
In this case, I would like to propose to use RichTextValueBuilder. The sample script is as follows.
Sample script:
function myFunction() {
const textsForStrikethrough = ["John"]; // Please set the texts you want to reflect the strikethrough.
const sheetName = "Sheet1"; // Please set the sheet name.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const range = sheet.getDataRange();
const modify = range.getValues().reduce((ar, e, r) => {
e.forEach((f, c) => {
textsForStrikethrough.forEach(g => {
const idx = f.indexOf(g);
if (idx > -1) ar.push({start: idx, end: idx + g.length, row: r, col: c});
});
});
return ar;
}, []);
const textStyle = SpreadsheetApp.newTextStyle().setStrikethrough(true).build();
const richTextValues = range.getRichTextValues();
modify.forEach(({start, end, row, col}) => richTextValues[row][col] = richTextValues[row][col].copy().setTextStyle(start, end, textStyle).build());
range.setRichTextValues(richTextValues);
}
Result:
When above script is run, the following results are obtained.
Input situation:
This is the sample input situation before the script is run.
Output situation 1:
In this case, const textsForStrikethrough = ["John"]; is used for the input situation.
Output situation 2:
In this case, const textsForStrikethrough = ["John", "Amy"]; is used for the input situation.
Note:
In this sample script, all values are retrieved from the sheet and search the texts and reflect the strikethrough. So when you want to use this script to the specific range, please modify const range = sheet.getDataRange(); for your situation.
For example, from your sample image, when you want to use this script to the column "B", please modify it to const range = sheet.getRange("B1:B" + sheet.getLastRow());.
References:
Class RichTextValue
Class RichTextValueBuilder
Added:
About your following 2nd question,
This is perfect! Only other request I have, is how would we modify it to where it is referencing a series of other cells to lookup the names? The list of names changes daily, so looking to have all inputs be able to update by a simple change of the names on the sheet rather than modifying the code. So say the names could be input in cell A10:A15. Pulling that list of names and updating the "textsForStrikethrough" logic.
in this case, I think that at first, how about retrieving the values of cells "A10:A15", and use them as textsForStrikethrough?
Sample script 2:
function myFunction2() {
// const textsForStrikethrough = ["John"]; // Please set the texts you want to reflect the strikethrough.
const sheetName = "Sheet1"; // Please set the sheet name.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const range = sheet.getDataRange();
const textsForStrikethrough = sheet.getRange("A10:A15").getValues().flat(); // Added
const modify = range.getValues().reduce((ar, e, r) => {
e.forEach((f, c) => {
textsForStrikethrough.forEach(g => {
const idx = f.indexOf(g);
if (idx > -1) ar.push({start: idx, end: idx + g.length, row: r, col: c});
});
});
return ar;
}, []);
const textStyle = SpreadsheetApp.newTextStyle().setStrikethrough(true).build();
const richTextValues = range.getRichTextValues();
modify.forEach(({start, end, row, col}) => richTextValues[row][col] = richTextValues[row][col].copy().setTextStyle(start, end, textStyle).build());
range.setRichTextValues(richTextValues);
}
In this script, the values of cells "A10:A15" in the sheet of sheetName are used as textsForStrikethrough.
Note:
Unfortunately, I cannot understand about your actual situation. So when above script cannot be used for your actual situation, can you provide your sample Spreadsheet for replicating the issue? By this, I would like to confirm it.
I am trying to combine rows of data where they match in Col A & Col B only.
In the example 1 - you can see 2 rows of Guitar D in Aisle 7 - Then the expected result of combining the duplicates together.
So combine the Qty`s together and list the latest date.
I am sorry I have no code to offer as an example as i cannot find something similar.
I do appreciate any help.
I believe your goal and situation as follows.
You want to achieve the image in your question.
Also, in your actual situation, the cells "A2:D" are used as the source range.
When the same values of "SKU" are existing and the values of "LOCATION" are different, the rows are not merged. Only when both values of "SKU" and "LOCATION" are the same, the rows are merged.
Pattern 1:
In this pattern, as your sample image, it supposes that the rows in the source sheet are sorted with "SKU", "LOCATION" and "DATE".
Sample script:
In this sample, it supposes that the source values are put in the sheet name of source and the output values are put to the sheet name of destination. So please modify them for your actual situation.
function myFnunction() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
// 1. Retrieve values from the source sheet.
const srcSheet = ss.getSheetByName("source");
const srcValues = srcSheet.getRange("A2:D" + srcSheet.getLastRow()).getValues();
// 2. Create an array for putting to the destination sheet.
const dstValues = srcValues.reduce((o, r) => {
if (r[0] == o.temp[0] && r[1] == o.temp[1]) {
o.temp[2] += r[2];
o.temp[3] = r[3];
} else {
o.ar.push(o.temp.length == 0 ? r : o.temp);
o.temp = r;
}
return o;
}, {ar: [], temp: []});
// 3. Put the values to the destination sheet.
const dstSheet = ss.getSheetByName("destination");
dstSheet.getRange(dstSheet.getLastRow() + 1, 1, dstValues.ar.length, dstValues.ar[0].length).setValues(dstValues.ar);
}
Pattern 2:
In this pattern, as your sample image, it supposes that the rows in the source sheet are NOT sorted with "SKU", "LOCATION" and "DATE".
Sample script:
In this sample, it supposes that the source values are put in the sheet name of source and the output values are put to the sheet name of destination. So please modify them for your actual situation.
function myFnunction() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
// 1. Retrieve values from the source sheet.
const srcSheet = ss.getSheetByName("source");
const srcValues = srcSheet.getRange("A2:D" + srcSheet.getLastRow()).getValues();
// 2. Create an array for putting to the destination sheet.
const dstObj = srcValues.reduce((o, r) => Object.assign(o, {[`${r[0]}_${r[1]}`]: (o[`${r[0]}_${r[1]}`] ? [o[`${r[0]}_${r[1]}`][0], o[`${r[0]}_${r[1]}`][1], o[`${r[0]}_${r[1]}`][2] + r[2], (o[`${r[0]}_${r[1]}`][3].getTime() < r[3].getTime() ? r[3] : o[`${r[0]}_${r[1]}`][3])] : r)}), {});
const dstValues = Object.values(dstObj);
// 3. Put the values to the destination sheet.
const dstSheet = ss.getSheetByName("destination");
dstSheet.getRange(dstSheet.getLastRow() + 1, 1, dstValues.length, dstValues[0].length).setValues(dstValues);
}
References:
getValues()
reduce()
Conditional (ternary) operator
setValues(values)
I am trying to compile data from one sheet containing order information to another sheets cell based on each customers name. I'd like to take the title of the column as well as the count for the item(s) they have ordered. I tried to brute force it with a formula in Google Sheets but the formula messes up and stops giving the correct information so I figured using a scripts function would be better for what I am trying to do. I made a new sheet to test a script on but have little experience and can't seem to make any progress.
I'd like to get the title(top row) of each column and the count of the item(s) into the order column on sheet2 base on the matching names on both sheets. If anyone could help or provide some insight it would be greatly appreciated.
Here is the code I came up with:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var orders = ss.getSheetByName("Sheet2");
var data = ss.getSheetByName("Sheet1");
var names = orders.getRange("Sheet2!A2:A5");
var name = names.getValues();
var startRow = 1
var endRow = ss.getLastRow()
var getRange = ss.getDataRange();
var getRow = getRange.getRow();
var title = data.getRange("Sheet1!B1:J1");
var item = title.getValues();
var itemCell = data.getRange("Sheet1!B2").getValue();
var orderCell = orders.getRange(2,2).getValue()
Logger.log(itemCell)
if(itemCell>=0){
orders.getRange(2,2).setValue("item1 x " +itemCell)
}
currently this only has the desired effect on one cell and does not complete the row and repeat on next column.
Here is how I adjusted the code to try and fit a larger data set:
function myFunction() {
const srcSheetName = "Test Data";
const dstSheetName = "Order Changes";
const ss = SpreadsheetApp.getActiveSpreadsheet();
// 1. Retrieve source values.
const srcSheet = ss.getSheetByName(srcSheetName);
//I changed values 1,1 to change the values that were retreived
const [[, ...header], ...srcValues] = srcSheet.getRange(1, 1,
srcSheet.getLastRow(), srcSheet.getLastColumn()).getValues();
// 2. Create an object using the source values.
const srcObj = srcValues.reduce((o, [a, ...v]) => {
const temp = v.reduce((s, r, i) => {
if (r.toString() != "") s += `${header[i]} ${r}`;
return s;
}, "");
return Object.assign(o, {[a]: temp || ""});
}, {});
// 3. Retrieve the header column of destination values.
const dstSheet = ss.getSheetByName(dstSheetName);
//I changed values 2 or 1 to adjust the destination of values
const dstRange = dstSheet.getRange(2, 1, dstSheet.getLastRow() - 1);
const dstValues = dstRange.getValues();
// 4. Create the output values using the header column and the object.
const putValues = dstValues.map(([a]) => [srcObj[a] || ""]);
// 5. Put the values.
dstRange.offset(0, 1).setValues(putValues);
}
after making the changes and running the code the values would either not appear or appear in the wrong column with incorrect data.
Goal of function Update:
Match names in Sheet2!A with names in Sheet1!F
If a match is found combine header and value of cells in Sheet1!N1:BQ.
This should be from the same row of the matched name in Sheet1!F (example:
John Smith lm14 1, lm25 2, lm36 1)
Place combined data into Sheet2!C
Repeat for every name in Sheet2!A
header and cell value should not be combined if value < 0
I hope this helps to clarify any misunderstanding.
Here is are better example images:
I believe your goal as follows.
In your goal, the upper image in your question is the output you expect, and the cells "B2" should be item1 1 item3 1 item6 2 item9 3 when the lower input situation is used.
You want to achieve this using Google Apps Script.
In order to achieve above, I would like to propose the following flow.
Retrieve source values.
Create an object using the source values.
Retrieve the header column of destination values.
Create the output values using the header column and the object.
Put the values.
Sample script:
Please copy and paste the following script to the script editor of the Spreadsheet and set the source sheet name and destination sheet name, and run myFunction.
function myFunction() {
const srcSheetName = "Sheet1";
const dstSheetName = "Sheet2";
const ss = SpreadsheetApp.getActiveSpreadsheet();
// 1. Retrieve source values.
const srcSheet = ss.getSheetByName(srcSheetName);
const [[, ...header], ...srcValues] = srcSheet.getRange(1, 1, srcSheet.getLastRow(), srcSheet.getLastColumn()).getValues();
// 2. Create an object using the source values.
const srcObj = srcValues.reduce((o, [a, ...v]) => {
const temp = v.reduce((s, r, i) => {
if (r.toString() != "") s += `${header[i]} ${r}`;
return s;
}, "");
return Object.assign(o, {[a]: temp || ""});
}, {});
// 3. Retrieve the header column of destination values.
const dstSheet = ss.getSheetByName(dstSheetName);
const dstRange = dstSheet.getRange(2, 1, dstSheet.getLastRow() - 1);
const dstValues = dstRange.getValues();
// 4. Create the output values using the header column and the object.
const putValues = dstValues.map(([a]) => [srcObj[a] || ""]);
// 5. Put the values.
dstRange.offset(0, 1).setValues(putValues);
}
References:
getValues()
setValues(values)
reduce()
map()
Added 1:
About your current issue, the reason of your issue is that the ranges of source and destination are the different from the sample image in your question. My suggested answer is for the sample images in your initial question. When you changed the structure of the Spreadsheet, it is required to modify my suggested script. But from I changed values 1,1 to change the values that were retrieved and I changed values 2 or 1 to adjust the destination of values, I couldn't understand about your modified script. So as the additional script, I would like to modify my suggested answer for your updated question.
From your updated question and replyings, I understood that the source range and destination range are "N1:BQ" and "A52:C79", respectively. From this, please modify above sample script as follows.
From:
const [[, ...header], ...srcValues] = srcSheet.getRange(1, 1, srcSheet.getLastRow(), srcSheet.getLastColumn()).getValues();
To:
const [[, ...header], ...srcValues] = srcSheet.getRange("N1:BQ" + srcSheet.getLastRow()).getValues();
and
From:
dstRange.offset(0, 1).setValues(putValues);
To:
dstRange.offset(0, 2).setValues(putValues);
Added 2:
About your current issue, the reason of your issue is that the ranges of source and destination are the different from your 1st updated question in your question. My suggested answer is for the sample images in your 1st updated question. When you changed the structure of the Spreadsheet, it is required to modify my suggested script.
From your 2nd updated question, I understood that the source range and destination range are "F1:BQ" (the column "F" is the title and the columns "N1:BQ" are the values.) and "A2:C", respectively. From this, please modify above sample script as follows.
function myFunction() {
const srcSheetName = "Sheet1";
const dstSheetName = "Sheet2";
const ss = SpreadsheetApp.getActiveSpreadsheet();
// 1. Retrieve source values.
const srcSheet = ss.getSheetByName(srcSheetName);
const [[,,,,,,,, ...header], ...srcValues] = srcSheet.getRange("F1:BQ" + srcSheet.getLastRow()).getValues();
// 2. Create an object using the source values.
const srcObj = srcValues.reduce((o, [a,,,,,,,, ...v]) => {
const temp = v.reduce((s, r, i) => {
if (r.toString() != "") s += `${header[i]} ${r}`;
return s;
}, "");
return Object.assign(o, {[a]: temp || ""});
}, {});
// 3. Retrieve the header column of destination values.
const dstSheet = ss.getSheetByName(dstSheetName);
const dstRange = dstSheet.getRange(2, 1, dstSheet.getLastRow() - 1);
const dstValues = dstRange.getValues();
// 4. Create the output values using the header column and the object.
const putValues = dstValues.map(([a]) => [srcObj[a] || ""]);
console.log(srcObj)
// 5. Put the values.
dstRange.offset(0, 2).setValues(putValues);
}