Transferring specific cell data from sheet to sheet - javascript

I have a problem where I need to transfer the cell data from one sheet to another. What I'm trying to achieve in the end is that if I click a button, it will import my data from the sheet one sheet to the sheet I'm currently using.
My original code looked like this:
function C2() {
var sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("C2");
var destSheet = SpreadsheetApp.getActiveSpreadsheet()
sourceSheet.getRange("A1:I43").copyTo(destSheet.getRange("A1:I43"), {contentsOnly:true});
}
But that won't work for the new modifications I've made. It's erasing the formulas in the cells on the next sheet and replacing them with the values of the previous sheet that the formulas produced.
I've tried to use this formula, selecting all of the areas that I'd like to transfer, but it results in a "range not found" error message.
function C1() {
var sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("C1");
var destSheet = SpreadsheetApp.getActiveSpreadsheet()
sourceSheet.getRange("A2,A4:B16,A21,A23,A25,A27,D3:D22,E4:E22,F3:H22,C24,C26:E31,F25,L1").copyTo(destSheet.getRange("A2,A4:B16,A21,A23,A25,A27,D3:D22,E4:E22,F3:H22,C24,C26:E31,F25,L1"), {contentsOnly:true});
}
If it's possible to cherry pick the cells I need and transfer them to my desired sheet instead of only using a broad range (ex. "A1:I43"), That would be ideal. Any and all help is very much appreciated.

You need to define a RangeList and iterate through all the contained ranges.
If you want to copy values only, getValues() and setValues() will be useful methods for you:
function myFunction() {
var spreadsheet=SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("C2");
var destSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var rangeList=sourceSheet.getRangeList(["A2","A4:B16","A21","A23","A25","A27","D3:D22","E4:E22","F3:H22","C24","C26:E31","F25","L1"]);
var rangeList2=destSheet.getRangeList(["A2","A4:B16","A21","A23","A25","A27","D3:D22","E4:E22","F3:H22","C24","C26:E31","F25","L1"]);
for (var i=0;i<rangeList.getRanges().length;i++){
rangeList2.getRanges()[i].setValues(rangeList.getRanges()[i].getValues());
}
}

Related

copyTo google sheet appscript

I'm very new to Javascript and Apps Script I'm looking to create a function that updates another sheet based on the date in a specific range of the active sheet. I run and there are no errors but it is not transferring the values from the active sheet to the named sheet "Feb".
Please help me see what I'm not seeing.
function updateYTD3() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("January");
const targetSheet = ss.getSheetByName("Feb");
if (sheet && targetSheet) {
if(sheet.getRange("A2:D32").getValues().length > 0){
sheet.getRange("A2:D32").copyTo(targetSheet.getRange("C2"),{contentsOnly:true});
}
}
}
but with funcition Loop and copy range based on criteria
but with funcition Loop and copy range based on criteria link
sample
The script is working just fine! But it overwrites previous data since it's stated to write it in C2. Do you expect to stack the values with the previous one?
Try changing "C2" with "C"+(targetSheet.getLastRow()+1)

Automating named Range function in google sheets

Context
So I have a spreadsheet with 11+ sheets, though will be adding more later. I want to dynamically name the columns using named range. I created a macro script and have been using this. Only the problem is for every sheet, I have to go to the script and change the name of the named range:
function NamedRanges() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.setNamedRange('TrainlineDate', spreadsheet.getRange('A:A'));
spreadsheet.setNamedRange('TrainlinePrice', spreadsheet.getRange('B:B'));
spreadsheet.setNamedRange('TrainlineReturns', spreadsheet.getRange('C:C'));
spreadsheet.setNamedRange('TrainlineGrossReturns', spreadsheet.getRange('D:D'));
spreadsheet.setNamedRange('TrainlineGeometricReturns', spreadsheet.getRange('E:E'));
spreadsheet.setNamedRange('TrainlineRisk', spreadsheet.getRange('F:F'));
spreadsheet.setNamedRange('TrainlineNegativeReturns', spreadsheet.getRange('G:G'));
spreadsheet.setNamedRange('TrainlinePositiveReturns', spreadsheet.getRange('H:H'));
spreadsheet.setNamedRange('TrainlineTimeValueMoney', spreadsheet.getRange('I:I'));
};
For example, for the next tab, I have to change Trainline to Softcat.
I tried my hand at creating the columns as an array and then a for loop to create a named range according to the name in cell B2 + the name in the headers (the 3rd row of every column). I will also be adding new columns in the future. But when I tried to log the value in cell B2 it failed. Long story short, I am stuck. This is what I came up with thus far;
function NamedRange() {
const ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var col = ss.getLastColumn(); //Get all the columns in the sheet with data (there will be no gaps/spaces)
var stockName = ss.getRange("B1"); // name in cell B1 (column 2, row 1)
var headerCell = ss.getRange(3, col); // in row 3 of all columns
var rangeName = ss.getValue(stockName);
Logger.log(rangeName) // test to see if the value of stockname is picked up by Appscript
// For every column, get the values in 'stockName and headerCell' and create a named range from them.
An exception is for the second column, instead of 'Close' name, call it 'Stockname' + 'Price'.
};
Here is an example of the spreadsheet format. This script though will be applicable to Aveva Group tab onwards.
Problem
Typically the format of the spreadsheets will all be the same. The only difference will be the name of the stock. I want to be able to automatically set the namedRange of all columns for existing and new columns for every tab/sheet and trigger it using a custom menu (this part I can sort out myself). Is there a better way to get this done?
Explanation:
Create an array of all the sheet names you would like to be part of this process.
ForEach sheet name, set the name ranges according to that name by concatenating the sheet name with the namerange name.
Solution:
function NamedRanges() {
var spreadsheet = SpreadsheetApp.getActive();
//put all the sheets here you want to include
var sheetNames = ["Trainline","Softcat","Avast"];
var namerng=['Date','Price','Returns','GrossReturns','GeometricReturns',
'Risk','NegativeReturns','PositiveReturns','TimeValueMoney'];
sheetNames.forEach(sh=>{
sheet = spreadsheet.getSheetByName(sh);
namerng.forEach((nr,i)=>{
spreadsheet.setNamedRange(sh+nr, sheet.getRange(1,i+1,sheet.getMaxRows(),1));
});
});
};
Save also this code to your script editor and it will create a menu button at the top menu of the spreadsheet file that will execute NamedRanges:
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Custom Menu')
.addItem('Name Ranges', 'NamedRanges')
.addToUi();
}

Copy filtered range from one spreadsheet to another - Google app script

I have a large google sheet with 30275 rows and 133 columns in a google sheet. I want to filter the data and copy column AZ to another spreadsheet.
Link to spreadsheet: https://docs.google.com/spreadsheets/d/1aiuHIYzlCM7zO_5oZ0aOCKDwPo06syXhWvhQMKgJE2I/edit?usp=sharing
I have been trying to follow this link
I am not that familiar with javascript and the code is designed to exclude items from filter rather than including items on filter. I have 500+ items to exclude so need to work out something that will be efficient in filtering large dataset in short time before execution limit is reached.
Here is my code so far. Any help to get this working would be appreciated.
NOTE: Filter/ Query with importrange formulas dont work due to the large volume of data. So I need an efficient script to filter large dataset and move them to another sheet before execution time limit.
function filtered() {
var ss = SpreadsheetApp.openById('1u9z_8J-tvTZaW4adO6kCk7bkWeB0pwPcZQdjBazpExI');
var sheet = ss.getSheetByName('Sheet1');
var destsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('JockeyList');
var demosheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Betting data - Demo');
var jockey = demosheet.getRange('L14').getValues();
// Get full (non-filtered) data
var values = sheet.getRange('A:EC').getValues();
// Apply filter criteria here
//Logger.log(jockey);
var hiddenValues = jockey;
values = values.filter(function(v) {
return hiddenValues.indexOf(v[51]) == 1;
});
Logger.log(values.length);
// Set filtered data on the target sheet
destsheet.getRange(10, 5, values.length, 2).setValues(values);
}
Ok so it seems like you want to copy only the values from AZ in 'Sheet1' that are equal to whatever string value is contained in cell L14 of sheet 'Betting data - Demo.' If that is the case, then here is a change to your original code that will accomplish that:
function filtered() {
var ss = SpreadsheetApp.openById('1u9z_8J-tvTZaW4adO6kCk7bkWeB0pwPcZQdjBazpExI');
var sheet = ss.getSheetByName('Sheet1');
// this assumes that your destsheet and demosheet are in the same spreadsheet. Keep in mind that opening spreadsheets with SpreadsheetApp is costly so you want to minimize your calls to new sheets.
var destsheet = ss.getSheetByName('JockeyList');
var demosheet = ss.getSheetByName('Betting data - Demo');
var jockey = demosheet.getRange('L14').getValue();
var searchTerm = new RegExp(jockey);
// Get full (non-filtered) data
var values = sheet.getRange('A:EC').getValues();
// Apply filter criteria here and return ONLY THE VALUE IN COLUMN AZ
var filteredValues = values.reduce(function(resultArray, row) {
if (searchTerm.test(row[51])) resultArray.push([row[51]]);
return resultArray;
}, [])
// Set filtered data on the target sheet
// Note* not clear why you are starting at row 10, but as is this will overwrite all of the data in column 5 of destsheet starting from row 10 every time this function runs
destsheet.getRange(10, 5, filteredValues.length, 1).setValues(filteredValues);
}
As it says in the code sample, this will only copy and paste the value in column AZ of 'sheet1'. It does not alter 'sheet1' in any way. If that is really all you want to do, then this function works, but it's overkill. Since you are just filtering values in AZ against a single string value, it would be more efficient to simply count the number of times that string occurs in column AZ and then add the string that number of times to your destination sheet.
Also note that your original function is pasting values into destsheet into a constant row (row 10). That means that every time your function runs, the data from row 10 on will be overwritten by whatever data you are copying from 'sheet1'

How to retrieve data column-wise in Spreadsheets

I have a spreadsheet with a lot of data. I need to retrieve this data column-wise (or row-wise if column-wise is too complicated). However I can't figure out a way to do this. I have the following working function which returns the data contained in a specific rectangular grid in the spreadsheet specified by row number, column number, number of rows, number of columns.
However, what I want to do, is simply mention the column number and get all the data in that column.
function getSpreadSheetData(){
var id= SpreadsheetApp.getActiveSpreadsheet().getId();
var ss = SpreadsheetApp.openById(id);
var sheets = ss.getSheets();
// the variable sheets is an array of Sheet objects
var sheetData = sheets[0].getRange(row, column, numRows, numColumns);
//consider row,column,numRows,numColumns = 2,1,2,2
return sheetData;
}
How should I modify this code?
How do you want to return it and to what?
it seems what you are trying to achieve can easily be done with:
function getSpreadSheetColumns(sheetName, c){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
return ss.getRange(1, c, ss.getLastRow()).getValues();
}
Possibly moving the sheet name inside the function if it will always be the same.

How can I make this series of java script variables into a function?

I am using node.js and the excel parser xlsx to do this. I have 3 different sheets in my example excel file. My code so far finds all the sheet names, and then the data in the sheet and then finds the data in the cell A1 based on which sheet I choose to find it in, in this case it's the sheet at index [0].
I want to be able to find this data in cell A1 but not by having to manually input which sheet, as I want the client to be able to choose the sheet from a drop down menu(which I already have the code for) and then have it show the data in A1 based on which sheet they pick. Therefore I was wondering how I could turn my code into a function so that instead of having [0], it is able to find the data in A1 based on the variable that is the client's pick from the menu.
var workbook = xlsx.readFile('C:/Users/user/Desktop/1234.xlsx');
var sheet_name = workbook.SheetNames[0];
var address_of_cell = 'A1';
var worksheet = workbook.Sheets[sheet_name];
var desired_cell = worksheet[address_of_cell];
var desired_value = desired_cell.v;
console.log(desired_value);
(the .v is just an input with the xlsx parser that presents the data as raw)
Just make a function out of it. If this isn't what you were asking for, please clarify a bit.
function getSheetData(workbook, sheetNumber, cellName) {
var workbook = xlsx.readFile(workbook);
var sheet_name = workbook.SheetNames[sheetNumber];
var address_of_cell = cellName;
var worksheet = workbook.Sheets[sheet_name];
var desired_cell = worksheet[address_of_cell];
var desired_value = desired_cell.v;
return desired_value;
}
// get the variables from the user input, and then run
// this.
var data = getSheetData('1234.xlsx', 0, 'A1');
console.log(data);

Categories

Resources