ljc
ljc

Reputation: 938

Move entire row when sorting column (Google Apps Script)

I have a list of names in Column B, and a bunch of data (ID number, bank account details, etc.) in columns C:AK that corresponds/belongs to the name in column B.

I want to sort column B alphabetically, but the entire rows data must move with the name when sorted.

E.g. Lets say Ted is in B2 and Amy is in B3. When I do myrange.sort(2), Ted will now move to B3, but C2:AK2 must also now become C3:AK3. Otherwise Amy's personal details will now show up in the same row as Ted.

Does that make sense?

Example code:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Summary');
var curRange = sheet.getRange("B2:B6");
curRange.sort(2);

Upvotes: 0

Views: 194

Answers (1)

Anton Dementiev
Anton Dementiev

Reputation: 5716

Your range only contains a single column so naturally, calling the 'sort()' method ignores all other columns in the sheet. You should select the entire data range and then sort by the selected column

 var sortRange = sheet.getRange("B2:AK");
 sortRange.sort({column:2, ascending: true});

Upvotes: 1

Related Questions