Merge cells with same words - google-apps-script

I created an array containing multiple rows and columns.
In column B, I have the type of vegetables, and in column c, the varieties.
In the array, there is an automatic sorting which is carried out in column B then column c.
Is it possible to merge automatically the cells of column B containing the same type?
I just know how to merge a range with :
var range1 = sheet.getRange("b4:b9");
range1.merge();
A test array here
Cordially.

How about this sample script? I think that there are several answers for this situation, so please think of this as one of them. The flow of this script is as follows.
Flow :
Retrieve values of column B.
Retrieve the number of duplication values.
Merge cells.
Sample script :
function myFunction() {
var start = 4; // Start row number for values.
var c = {};
var k = "";
var offset = 0;
var ss = SpreadsheetApp.getActiveSheet();
// Retrieve values of column B.
var data = ss.getRange(start, 2, ss.getLastRow(), 1).getValues().filter(String);
// Retrieve the number of duplication values.
data.forEach(function(e){c[e[0]] = c[e[0]] ? c[e[0]] + 1 : 1;});
// Merge cells.
data.forEach(function(e){
if (k != e[0]) {
ss.getRange(start + offset, 2, c[e[0]], 1).merge();
offset += c[e[0]];
}
k = e[0];
});
}
Result :
Note :
This sample script supposes that the values of column B is sorted.
From your shared spreadsheet, it supposes that there are the values for merging cells at column B.
In your shared spreadsheet, the order of sorted values is Composées, Cucurbitacées, Légumineuses, Liliacées, Solanacées. On the other hand, the order of "Wish" is Composées, Cucurbitacées, Légumineuses, Solanacées, Liliacées.
I couldn't understand the difference logic between Liliacées, Solanacées and Solanacées, Liliacées.
In this sample script, it uses the order of sorted values.
Reference :
merge()
If I misunderstand your question, I'm sorry.
Edit 1 :
For your next question, I think that the following flow can achieve what you want. But I think that there may be other solution.
Add values by an user.
Break the merged cells using breakApart().
For example, it merges cells of "A1:A3" which have the values of "sample", "sample", "sample". When this merged cell is broken using breakApart(), each value of "A1:A3" retrieved by getValues() becomes [["sample"],[""],[""]].
Fill the empty cells created by breakApart().
Sort the cells.
Run the sample script on my answer.
Reference :
breakApart()
Edit 2 :
Usage of breakApart():
If you want to break "B1:B", please use as follows.
var ss = SpreadsheetApp.getActiveSheet();
ss.getRange("B1:B").breakApart()

Related

Google Sheet Macro - how do I return a column number based on dynamic cell contents?

I have the following code as a starting point. I want to select the entire column where row 3 contains a specific date value (it will be the date of the previous Monday; I have a formula returning this date in cell E1).
function selectDate() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
ss.getRange(3,?,1,ss.getMaxColumns()).activate();
}
Basically, the getRange column value would be interpreted as something like: "Find the column number where the value in row 3 is equal to the value in cell E1".
Any ideas would be very helpful, even if it's using a totally different method to achieve the same thing. Thank you so much!
In your situation, how about the following sample script?
Sample script:
function selectDate() {
var sheet = SpreadsheetApp.getActiveSheet();
var searchValue = sheet.getRange("E1").getDisplayValue();
var res = sheet.getRange(3, 1, 1, sheet.getLastColumn()).createTextFinder(searchValue).matchEntireCell(true).findNext();
if (!res) return;
var column = res.getColumn();
sheet.getRange(1, column, sheet.getLastRow()).activate(); // Here, the found column is activated.
Browser.msgBox("Found column number is " + column); // Here, the found column number is shown in a dialog.
}
From your situation, I thought that getRange(3,?,1,ss.getMaxColumns()) in your script might be getRange(3, 1, 1, sheet.getLastColumn()).
When this script is run, row 3 is searched using the value of cell "E1". When the value is found, as a sample, the found column is activated and the column number is shown in a dialog. This is a sample. Please modify this for your actual situation.
Note:
If no column is selected, it is considered that the value of cell "E1" is not found in row 3. At that time, can you provide the detail of your Spreadsheet? By this, I would like to modify it.
Reference:
createTextFinder(findText) of Class Range

Create grouping in Google Sheets

I want to implement Groups in Google Sheets via API(appscript) as the direct method doesn't works dynamically. I have a column named levels(0-8) and then two more columns(other info). I want to write a script to make the groups. It will check the first column which has levels and if the next row has level more than the current i level, it will make a group of those rows until a row comes which has the same level or less than the i level. For example, levels are: 1,2,3,4,1,0,3,4. In this it will start from 1 and make the group of 2,3,4 as they are greater than 1. Skip 1,0 as they are equal or less than that and then make a group of 3,4. It will then run for 2 and do the same, make a group for 3,4 and skipping 1,0 and then make a group for 3,4.
Here is the link: https://docs.google.com/spreadsheets/d/1Ejbkl2imgEFi2mVwQ81xF5OkC97IXc4UcQIC3dxwPh4/edit?usp=sharing
Here's the code:
function myFunction() {
const rootSheet = SpreadsheetApp.getActive().getActiveSheet();
var r = rootSheet.getLastRow();
for (var i = 3; i <= r; i++) {
var t = 0;
do {
rootSheet.getRange(i,6).shiftRowGroupDepth(1);
t = t + 1;
} while (SpreadsheetApp.getActiveSheet().getRange(i,1).getValue() == t)
}
}
Here's how manually I have achieved grouping as per the pictures: https://drive.google.com/file/d/1JthF2ZJXgj5--0IOnW1LCM5Pneo9XUxJ/view?usp=sharing https://drive.google.com/file/d/1JthF2ZJXgj5--0IOnW1LCM5Pneo9XUxJ/view?usp=sharing
Modification points:
In your script, it seems that the values from the column "A" in "Sheet1" are not used for the group depth.
In this case, I would like to propose the following flow.
Retrieve values from the column "A".
Set the group depth using the retrieved values.
Modified script:
function myFunction() {
const sheetName = "Sheet1";
// 1. Retrieve values from the column "A".
const rootSheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
const levels = rootSheet.getRange("A2:A" + rootSheet.getLastRow()).getValues();
// 2. Set the group depth using the retrieved values.
levels.forEach(([a], i) => rootSheet.getRange(i + 2, 1).shiftRowGroupDepth(a));
}
Result:
When above script is used for your shared Spreadsheet, the following result is obtained.
Reference:
shiftRowGroupDepth(delta)

Fetch text string from specific column and select range of that string

I have shared below link of my sheet.
I tried every possible script to accomplish below task in the end in frustration i wipe out my whole script.
I would like to match text from column A and return or getValue of corresponding B column.
So I can use that getValue from its corresponding B column for further arithmetic operations.
Thank you.
sheet link - https://docs.google.com/spreadsheets/d/1SwYYacz9A9s6ZXrL44KtRN7gqnwXkhu4cDILdUA1iJQ/edit?usp=sharing
Basic steps:
Retrieve your data range
Form an 1D array out of your column A entries, e.g. with map()
Check either the search string is contained in the array - and if yes retrieve its position - e.g. with indexOf()
Retrieve the value with the respective row index in column B
Sample:
function myFunction() {
var matchText = "C";
var values = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getDataRange().getValues();
var columnA =values.map(function(e){return e[0]});
var row = columnA.indexOf(matchText);
if (row >= 0){
var Bvalue = values[row][1];
Logger.log(Bvalue);
}
}
I encourage you to take some time to study Apps Script, so you cannot only understand this code and adapt to your needs, but also write your own scripts.

compare two colums in different spreadsheets in google script

i want to compare tow different columns in two different spreadsheets.
My first spreadsheet is named "testtabelle" and the other is named "test" the name of the sheets are both "Tabellenblatt1"
I want to compare column A # testtabelle with column A # test.
If the string are equal, i need the value from colum B # test and copy it into column b # testtabelle of the same row, where my strings matched.
I think i need two loops for every column and a if statement to compare the values.
I'll be glad if someone can help me!
You can use the SpreadsheetApp class to open multiple sheets. Look up openById or openByUrl, either should work. You can then make two spreadsheet objects, get the values of column A and B of each, iterate through to compare, and copy the value of column B if the values of column A match.
One thing to note is you should use getValue and setValue rather than copyTo as I don't think the latter works across separate spreadsheets.
You should end up with something like this:
// gets spreadsheet A and the range of data
ssA = SpreadsheetApp.openById('ID of spreadsheet A');
sheetA = ssA.getSheetByName('name of sheet in ssA');
dataA = sheetA.getRange('A:B').getValues();
// gets spreadsheet B and the range of data
ssB = SpreadsheetApp.openById('ID of spreadsheet B');
sheetB = ssB.getSheetByName('name of sheet in ssB');
dataB = sheetB.getRange('A:B').getValues();
// loops through column A of spreadsheet A & B and compares
for(var i = 0; i > sheetA.getLastRow(); i++){
// checks to see if ith value in 2nd row is the same
if dataA[1][i] == dataB[1][i]{
var value = sheetA.getRange(i+1, 2).getValue();
// used i+1 because index of range is 1, while index of the data array is 0
sheetB.getRange(i+1, 2).setValue(value);
} // end if
} // end i
There's also a similar question answered here.

Google Spreadsheet script to merge cells in column A containing 'Hello' with the adjacent cell in column B

I'm trying to merge cells containing a certain word in column A (e.g. 'Hello') with the cell to the immediate right (in column B)
E.g. A4 = 'Hello', therefore I would like to merge cells A4 and B4.
I have this code so far:
function formatCells() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Combined');
var range = s.getDataRange()
var values = range.getValues();
for( var row = values.length -1; row >= 0; --row )
if (values[row][1] == 'Hello')
{s.getRange(row+1,1).mergeAcross();
}
}
But the code doesn't seem to be doing anything at all? Can anyone out there kindly tell me what I'm doing wrong?
Many thanks for looking.
Arrays are 0 indexed,so column A is index 0...
You should simply use values[row][0] in your condition.
And to mergeAcross two cells you'll need to get a 2 cells range like this :
s.getRange(row+1,1,1,2).mergeAcross();
Note also that you will loose the value that was in column B since the merge method doesn't merge contents. I don't know if thar's an issue for you...