jignesh
jignesh

Reputation: 786

Google App Script to combine columns

I have a google spreadsheet with multiple columns that have variable row counts in each column. I would like to combine all the columns into one column.

So if the following is the data: Column 1, column 2, Column 3, Column 4 Row 1: A, B, C, D Row 2: ,,,E

I would want to get Row 1: A Row 2: B Row 3: C Row 4: D Row 5: E

I would like this to be non-destructive to the original sheet so it should create a new spreadsheet tab with a unique name. The unique name is important b/c i would like to run this function on multiple spreadsheets that are all different. The unique name will avoid overlap.

The request is to help me write the script to do this transpose in google apps spreadsheets

Thank you for the help!

Upvotes: 1

Views: 6173

Answers (1)

Andrei Urse
Andrei Urse

Reputation: 89

Here is the script, please let me know if you encounter any issues, at the moment it ignores blank cells and the value "0".

function myFunction() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = spreadsheet.getSheets()[0];
  var lastRow = sheet1.getLastRow();
  var lastColumn = sheet1.getLastColumn();
  var values = sheet1.getRange(1, 1, lastRow, lastColumn).getValues();
  var d = new Date();
  var newSheet = spreadsheet.insertSheet("Sheet: "+d.getTime());
  var counter=1;
  for (var i=0;i<=lastRow-1;i++) {
    for (var j=0;j<=lastColumn-1;j++) {
      if(values[i][j]!="") {
        newSheet.getRange(counter,1).setValue(values[i][j]);
        counter++;
      }
    }
  }
}

Upvotes: 2

Related Questions