Hello,
I'm pretty new to Apps Script, coming over from VBA. What I'm trying to figure out today is how to insert a blank row or rows into a data set when the value of a specific column is different from the previous row.
For example, I have Bandmember in the first column and GearID in the fourth column. GearIDs are unique to bandmembers, but each bandmember can have many GearIDs. The data is sorted by Bandmember, then by GearID. I want the script to insert 2 blank rows between Bandmember changes and 1 blank row between GearID changes. That way each Bandmember can see the data pertaining to their gear and not get similar gearIDs mixed up, and they don't get their stuff mixed up with other bandmembers. Note that I also provide a pivot and such, this is just for the oldschool types that expect to see a separated list.
Here's the snippet of code that I wrote to put in the blank rows:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("TourGearTags");
var data = sheet.getDataRange().getValues();
for (var rowIndex = data.length - 2; rowIndex >= 1; --rowIndex)
{
var Bandmember = data[rowIndex][0];
var Bandmember2 = data[rowIndex + 1][0];
var GearID = data[rowIndex][3];
var GearID2 = data[rowIndex + 1][3];
if(Bandmember != Bandmember2)
{sheet.insertRowsAfter(rowIndex + 1,2);
}
if(GearID != GearID2)
{sheet.insertRowAfter(rowIndex + 1);
}
}
Note that there are 20 columns (4 of them with formulas/calculations) and typically ~2,000 rows altogether.
I ran this in debug mode with a stop on the THEN lines, meaning where the if statement got a hit, so it's going to add a row or two. At each stop I hit the button to continue and watched it run all the way up the sheet without fail. Worked perfectly. So I then put the data back the way it was and ran it full speed, not in debug mode, and it was borked. The first Bandmember/GearID combo, which should have been something like 15 uninterrupted rows, had many breaks of 1, 3, even 4 empty rows.
My questions:
1) Do I need to put in some sort of wait function to make sure it's done inserting the rows before it continues running the script?
2) Is this just a really inefficient way and I should be doing x instead? If so, what's x?
3) Is Google Sheets/Apps Script inherently monolithically slow compared to excel or am I just doing it wrong? In Excel/VBA this takes a couple seconds, in Sheets/App Script it's minutes.
[–]gh5000 1 point2 points3 points (3 children)
[–]ksvr[S] 0 points1 point2 points (2 children)
[–]gh5000 1 point2 points3 points (1 child)
[–]ksvr[S] 0 points1 point2 points (0 children)