Reputation: 13
Total beginner here. I am trying to select columns A,B,C from spreadsheet B which has around 40K rows and 25 columns, to spreadsheet A which is a blank document. So, I have two spreadsheets. This code works fine but I want to select only the columns I need (columns including all the data, not just the headers).
function importdata() {
let ss = SpreadsheetApp.openById("ID"); //SPREADSHEET TO COPY FROM
let sheet = ss.getSheetByName("name"); //SHEET (TAB) TO COPY FROM
sheet.getRange(1,1,sheet.getLastRow(),sheet.getLastColumn()).getValues();
let ssThis = SpreadsheetApp.getActiveSpreadsheet();
let sheetRawData = ssThis.getSheetByName("name"); //SHEET IN THE TARGET SPREADSHEET TO COPY TO
sheetRawData.getRange(1,1,sheetRawData.getLastRow());
}
Any idea as to how I can add this into the code above? Many thanks!
Upvotes: 1
Views: 6698
Reputation: 26816
function importSelectedColumns() {
let selectedColumns = [1, 3, 5];
let ss = SpreadsheetApp.openById("ID"); //SPREADSHEET TO COPY FROM
let sheet = ss.getSheetByName("name"); //SHEET (TAB) TO COPY FROM
let ssThis = SpreadsheetApp.getActiveSpreadsheet();
let sheetRawData = ssThis.getSheetByName("name"); //SHEET IN THE TARGET SPREADSHEET TO COPY TO
selectedColumns.forEach(function(column){
let data = sheet.getRange(1,column, sheet.getLastRow(),1).getValues();
sheetRawData.getRange(1,column, sheet.getLastRow(), 1).setValues(data);
})
}
Explanation:
Additional information:
If you would like to paste your data into an adjacent range starting with column 1, one possible way based on the sample above would be to redefine the loop as following:
selectedColumns.forEach(function(column,i ){
let data = sheet.getRange(1,column, sheet.getLastRow(),1).getValues();
sheetRawData.getRange(1,1+i, sheet.getLastRow(), 1).setValues(data);
})
Thereby the counter variable i
is introduced and the notation of the destination column is modified from column
to 1+i
, meaning that the columns will be set starting with column 1
and increasing by 1
for each loop iteration.
Upvotes: 1