baldalbino
baldalbino

Reputation: 17

Is there an easy format to move columns of data by script?

I want to move several rows from one sheet to another but all the scripts that I am looking at don't see to address this.

For example, I want to move Column A,B,C on Sheet1 to Column G,I,L on Sheet2.

Can this be done? I am very new to scripting and don't have an example of what I am doing.

Thanks.

Upvotes: 0

Views: 3236

Answers (1)

JPV
JPV

Reputation: 27242

This could be done with simple code:

function moveCols() {
var ss = SpreadsheetApp.getActive();
var sourceSheet = ss.getSheetByName('Sheet1');
var destSheet = ss.getSheetByName('Sheet2');
sourceSheet.getRange('A:A').moveTo(destSheet.getRange('G1'))
sourceSheet.getRange('B:B').moveTo(destSheet.getRange('I1'))
sourceSheet.getRange('C:C').moveTo(destSheet.getRange('L1'))
}

If you only want to copy the data (and not move it) change the .moveTo() method to copyTo().

EDIT: If you need to move the columns to another spreadsheet, try:

function moveCols() {
var sourceSheet = SpreadsheetApp.getActive()
    .getSheetByName('Sheet1'),
    destSheet = SpreadsheetApp.openById('ID_OF_DESTINATION_SHEET')
        .getSheetByName('Sheet2'),
    sourceRanges = ['A:A', 'B:B', 'C:C'],
    targetRanges = [7, 9, 12]
        .map(function (r, i) {
            var sr = sourceSheet.getRange(sourceRanges[i]),
                val = sr.getValues();
            destSheet.getRange(1, r, val.length, val[0].length)
                .setValues(val);
            sr.clear()
        });
}

Upvotes: 5

Related Questions