What do I need to change in my script to find and replace all instances of a value in the range A1:G on the Original Sheet with the new value in B4 on the New Sheet?
Currently, the script looks at the value in B2 on the New Sheet, checks it against the range A1:G on the Original Sheet, but only replaces the first found value with the value in B4 on the New Sheet.
My Script
function replaceIds() {
const newss = SpreadsheetApp.openById("Sheet ID here")
const newSheet = newss.getSheetByName("New Sheet")
const originalss = SpreadsheetApp.openById("");
const originalSheet = originalss.getSheetByName("Sheet ID here")
const oldIds = newSheet.getRange("B2").getValues().flat()
const newIds = newSheet.getRange("B4").getValues().flat()
const rangeToCheck = originalSheet.getRange("A1:G")
oldIds.forEach(function(id, index) {
let cell = rangeToCheck.createTextFinder(id).findNext()
if (cell) {
cell.setValue(newIds[index])
}
})
}
I would like all instances of the value in cell B2 on the New Sheet found in the range A1:G on the Original Sheet to get replaced.
What lines do I need to modify and what do I replace them with?
I have seen similar questions but cannot figure out to to implement the answers.
Use .findAll(), like this:
oldIds.forEach((id, index) => {
const cells = rangeToCheck.createTextFinder(id).findAll();
cells.forEach(cell => cell.setValue(newIds[index]));
});
Related
We want to make a Google Form where there are dropdown options pulled from column F of the sheet (Sheet1), beginning in row 3 on down. However, column F has formulas in it, specifically: =IF(D$="","", CONCATENATE(C$," - ",D$)), so that some of the cells appear blank while others have visible text.
The code we attempted to use below does not work. Any help on how to make this work by pulling choices from column F, but of course ignoring blank cells?
var form = FormApp.openById('1Hg4TvEZUnzIMZI_andbwHQ3jtaIBLOZsrTkgjSwVcAY')
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
const current = sheet.getRange(3,6,sheet.getLastRow()-1,6).getValues()
var range = sheet.getDataRange();
var rangeList = current.map(function (row, i) {
for (var i=rangeList; i<range.length; i++) {
if (row[5] == "") return;
var matched = row[5];
const Question = form.getItemById ("620176576")
Question.asListItem().setChoiceValues(matched)
}
})
}
You've to use filter to only get the values which are not null.
Try below sample script:-
const form = FormApp.openById('1Hg4TvEZUnzIMZI_andbwHQ3jtaIBLOZsrTkgjSwVcAY')
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1')
const current = sheet.getRange(3,6,sheet.getLastRow()-3).getValues().flat().filter(r=> r) //filtering out blank values
const Question = form.getItemById("620176576")
Question.asListItem().setChoiceValues(current)
Reference:
filter()
I have been trying to create a simple filter using Google Sheets App Script. That if cell C2 values contains `RAM' then Col"2" should hide all rows except 'RAM'. But its not working.
I have created a data validation in cell C2 which changes the value. Any help will be appreciated.
function create_filter(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet1 = ss.getSheetByName("Filter_Sheet");
const range = sheet1.getRange("A5:T");
const filter = range.createFilter();
const Filter_Criteria1 = Sheet1.range('C2').getActiveCell;
const coll1 = 2
const add_filter = filter.setColumnFilterCriteria(coll1,Filter_Criteria1);
}
another try:
function create_filter(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet1 = ss.getSheetByName("Filter_Sheet");
const range = sheet1.getRange("A4:T");
const filter = range.createFilter();
var range2 = SpreadsheetApp.getActiveSheet().getRange('D2');
var range3 sheet1.getRange('C2').activate();
var criteria = SpreadsheetApp.newFilterCriteria()
.setHiddenValues([cell != range2 ])
.build();
spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(3, criteria);
};
I believe your goal is as follows.
You want to create the basic filter that when a text of RAM is contained to the cell value, you want to show the rows.
In this case, how about the following modification?
Modified script:
function create_filter() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet1 = ss.getSheetByName("Filter_Sheet");
const range = sheet1.getRange("A5:T");
const filter = range.createFilter();
filter.setColumnFilterCriteria(2, SpreadsheetApp.newFilterCriteria().whenTextContains("RAM").build());
}
In your 2 scripts, 2 ranges of const range = sheet1.getRange("A5:T") and const range = sheet1.getRange("A4:T") are used. In this modification, const range = sheet1.getRange("A5:T") is used. About this, please modify it for your actual situation.
When this script is run, the rows that RAM is contained at the value of column "B" are shown.
References:
setColumnFilterCriteria(columnPosition, filterCriteria)
Class FilterCriteriaBuilder
Added 1:
From the following replying in the comment and your script,
I have created a data validation in cell C2 there are 10 to 11 different string in that validation including RAM. So i want to create a on edit function that whenever Cell C2 string changes script should RUN and Column B will show exact value that is available in cell C2
I thought that the sheet name is "Filter_Sheet" and the data validation is put to the cell "C2". But, when I saw your Spreadsheet, the sheet name is "Sheet1" and the data validation is put to the cell "C1". So the following sample script uses your sample Spreadsheet. When you change the sheet name, please modify Sheet1 to others.
function onEdit(e) {
const offset = 0; // When the data validation is cell "C1" and "C2", please use 0 and 1, respectively.
const {range, value} = e;
const sheet = range.getSheet();
if (sheet.getSheetName() != "Sheet1" || range.getA1Notation() != "C" + (1 + offset)) return;
const r = sheet.getRange(`A${4 + offset}:T`);
const filter = sheet.getFilter();
if (filter) {
filter.remove();
}
r.createFilter().setColumnFilterCriteria(2, SpreadsheetApp.newFilterCriteria().whenTextContains(value).build());
}
From your following replying,
exactly the details are different because it is just sample sheet i can modify the code later when apply to real sheet
Please modify above script for your actual situation.
Added 2:
From your following replying,
but i am unable to edit this code. It is difficult for me to understand it, const value = sheet1.getRange('C2').getValue(); if this can be used then i can change the cell reference.
You want to run the script when the cell "C1" is edited. From your additional question, I understood like this. So, I proposed the modified script for using the event object of OnEdit simple trigger. But, when you don't want to use the event object, how about the following script?
function onEdit() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet1 = ss.getSheetByName("Sheet1");
const value = sheet1.getRange('C1').getValue();
const range = sheet1.getRange("A4:T");
const filter = sheet1.getFilter();
if (filter) {
filter.remove();
}
range.createFilter().setColumnFilterCriteria(2, SpreadsheetApp.newFilterCriteria().whenTextContains(value).build());
}
I got a filter in previous tabs, I can see the first row in those tabs with a dropdown that I can select/filter. Then I create a tab within the same spreadsheet and wanted to use the exact same first row as previous tabs. So I copied the first row to the new tab, but only text is copied but not the filter itself. Thanks.
You need to use a script. Here it is (Replace Sheet1 and Sheet2 with your tab names):
const SRC = 'Sheet1'
const DST = 'Sheet2'
function copyFilter() {
const ss = SpreadsheetApp.getActive()
const shSrc = ss.getSheetByName(SRC)
const shDst = ss.getSheetByName(DST)
const existingFilter = shDst.getFilter()
if(existingFilter){
existingFilter.remove()
}
const headerRange = shSrc.getDataRange().offset(0,0,1)
const filterRange = shDst.getRange(headerRange.getA1Notation())
filterRange.setValues(headerRange.getValues())
filterRange.createFilter()
}
I have a sheet where one column contains an ID to a Jira ticket.
I would like to automatically convert this to a link to the ticket, based on the value I enter.
E.g. I'll enter SD-1234 into the column, and I would like it to then make it into a clickable link to https://demo.atlassian.net/browse/SD-1234/, but not show the URL int he cell, but the original value I entered (SD-1234).
The column is always E if that helps. Can someone give me a head start with how to script this in Script Editor?
For example, when the cell "E1" has SD-1234, =HYPERLINK("https://demo.atlassian.net/browse/"&E1, E1) is used, the value is SD-1234 with the hyperlink of https://demo.atlassian.net/browse/SD-1234. But in this case, the result cannot be directly shown in the cell "E1". When you want to directly convert SD-1234 in the cell "E1" to SD-1234 with the hyperlink of https://demo.atlassian.net/browse/SD-1234, how about the following sample script?
Sample script:
Please copy and paste the following script and run the function at the script editor. Before you use this, please set the sheet name.
This sample script converts from SD-1234 in the column "E" to =HYPERLINK("https://demo.atlassian.net/browse/SD-1234", "SD-1234").
function sample1() {
const sheetName = "Sheet1"; // Please set the sheet name.
const baseUrl = "https://demo.atlassian.net/browse/";
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const range = sheet.getRange("E1:E" + sheet.getLastRow());
const values = range.getValues().map(([e]) => [`=HYPERLINK("${baseUrl}${e}", "${e}")`]);
range.setFormulas(values);
}
This sample script converts from SD-1234 in the column "E" to SD-1234 with the hyperlink of https://demo.atlassian.net/browse/SD-1234. In this case, the formula is not used.
function sample2() {
const sheetName = "Sheet1"; // Please set the sheet name.
const baseUrl = "https://demo.atlassian.net/browse/";
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const range = sheet.getRange("E1:E" + sheet.getLastRow());
const values = range.getValues().map(([e]) => [SpreadsheetApp.newRichTextValue().setText(e).setLinkUrl(baseUrl + e).build()]);
range.setRichTextValues(values);
}
Note:
If your spreadsheet has the 1st header row, please modify "E1:E" + sheet.getLastRow() to "E2:E" + sheet.getLastRow().
References:
map()
Class RichTextValueBuilder
setRichTextValues(values)
Added 1:
From your following comments,
Do I have to set the sheet name? I have several sheets that I always want this function to be applied to (I have currently over 20 sheets in the file).
Also, I've entered this into Script Editor to test, and what do I do from here? There's no save that I can see... and it's not running on my sheet. How can I apply this to my sheet to automatically run whenever a value is entered in the cell?
When the above situations are reflected in the script, it becomes as follows.
Sample script:
Please copy and paste the following script to the script editor and save it. And please edit the column "E" of the sheet. By this, the cell has the hyperlink with the inputted text.
function onEdit(e) {
const sheetNames = ["Sheet1", "Sheet2",,,]; // Please set the sheet names you want to run the script.
const column = 5; // Column E. From your question, this script run for the column "E".
const {range} = e;
const sheet = range.getSheet();
const baseUrl = "https://demo.atlassian.net/browse/";
if (!sheetNames.includes(sheet.getSheetName()) || range.columnStart != column) return;
const values = range.getValues().map(([e]) => [SpreadsheetApp.newRichTextValue().setText(e).setLinkUrl(baseUrl + e).build()]);
range.setRichTextValues(values);
}
If you want to run the script for all sheets, you can use the following script.
function onEdit(e) {
const column = 5; // Column E. From your question, this script run for the column "E".
const {range} = e;
const sheet = range.getSheet();
const baseUrl = "https://demo.atlassian.net/browse/";
if (range.columnStart != column) return;
const values = range.getValues().map(([e]) => [SpreadsheetApp.newRichTextValue().setText(e).setLinkUrl(baseUrl + e).build()]);
range.setRichTextValues(values);
}
Added 2:
If you want to run the script to the column "E" of all sheets by one script running, you can also use the following script.
Sample script:
This sample script runs for the specific sheets.
function myFunction() {
const sheetNames = ["Sheet1", "Sheet2",,,]; // Please set sheet names you want to run the script.
const baseUrl = "https://demo.atlassian.net/browse/";
SpreadsheetApp.getActiveSpreadsheet().getSheets().forEach(sheet => {
if (!sheetNames.includes(sheet.getSheetName())) return;
const range = sheet.getRange("E1:E" + sheet.getLastRow());
const values = range.getValues().map(([e]) => [SpreadsheetApp.newRichTextValue().setText(e).setLinkUrl(baseUrl + e).build()]);
range.setRichTextValues(values);
});
}
This sample script runs for all sheets.
function myFunction() {
const baseUrl = "https://demo.atlassian.net/browse/";
SpreadsheetApp.getActiveSpreadsheet().getSheets().forEach(sheet => {
const range = sheet.getRange("E1:E" + sheet.getLastRow());
const values = range.getValues().map(([e]) => [SpreadsheetApp.newRichTextValue().setText(e).setLinkUrl(baseUrl + e).build()]);
range.setRichTextValues(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);
}