Get range of a sheet up to the last cell containing data - javascript

I want to select the range of 2 columns till the last row with a value. Now I use this code:
var test = declSheet.getRange('Potjes!A:B');
Form this sheet:
The result I get is this:
How can I select till the last row with value?

You can use Sheet.getDataRange function which:
Returns a Range corresponding to the dimensions in which data is
present.
It seems like you are only interested in column A and B so:
// var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// var sheet = spreadsheet.getActiveSheet();
var dataRange = sheet.getDataRange();
var desiredRange = sheet.getRange("A1:B" + dataRange.getLastRow());
// desiredRange will consist of A1:B5 in OP example

Related

How do I fix a google script error that says coordinates of target range are outside the dimensions of the sheet when trying to archive? [duplicate]

I have been using a script in my google sheet that I found here:
copy data from one sheet to another in google app script and append a row, one small issue
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ss.getSheetByName("Copy");
var pasteSheet = ss.getSheetByName("Paste");
// get source range
var source = copySheet.getRange(2,2,12,2);
// get destination range
var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,2,12,2);
// copy values to destination range
source.copyTo(destination);
// clear source values
source.clearContent();
}
When I am running it now it gives me an error:
The coordinates of the target range are outside the dimensions of
the sheet.
which wasn't coming up before. Does anyone have an idea why it is doing this?
Issue:
The error is in this line:
var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,2,12,2);
pasteSheet.getLastRow() returns a row number which is at the very bottom of your sheet. Then you consider 12 rows range but the pasteSheet does not have 12 rows after the last row with content.
Solutions:
Add more rows in the pasteSheet:
or you can use insertRowsAfter:
pasteSheet.insertRowsAfter(pasteSheet.getLastRow(), 12)
Code snippet:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ss.getSheetByName("Copy");
var pasteSheet = ss.getSheetByName("Paste");
// get source range
var source = copySheet.getRange(2,2,12,2);
// insert rows to make sure you have enough space
pasteSheet.insertRowsAfter(pasteSheet.getLastRow(), 12)
// get destination range
var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,2,12,2);
// copy values to destination range
source.copyTo(destination);
// clear source values
source.clearContent();
}

Trying to do Dynamic Equity Split calculations in Google Sheets

new to using javascript in Google Sheets. I am trying to create a sheet that automatically calculates what business partners will receive based upon their dynamic split percentage and the incoming money. The percentage comes from one cell, but each payment made to the partners will be entered in a column. Here's what I have so far:
/**
* Creates a Date Stamp if a column is edited.
* Also performs dynamic split calculations
*/
//CORE VARIABLES
// The column you want to check if something is entered.
var COLUMNTOCHECK = 13;
// Where you want the date time stamp offset from the input location. [row, column]
var DATETIMELOCATION = [0,-1];
// Where the calculations will be performed for the Partners.
var PARTNERONELOCATION = [0, 1];
var PARTNERTWOLOCATION = [0, 2];
var PARTNERTHREELOCATION = [0, 3];
// Sheet you are working on
var SHEETNAME1 = 'Sheet1'
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var partnerOnePercent = sheet.getRange("G2").getValue();
var partnerOnePaySource = sheet.getRange("M2").getValue();
var partnerTwoPercent = sheet.getRange("G3").getValue();
var partnerTwoPaySource = sheet.getRange("M2").getValue();
var partnerThreePercent = sheet.getRange("G4").getValue();
var partnerThreePaySource = sheet.getRange("M2").getValue();
//checks that we're on the correct sheet.
if(sheet.getSheetName() == SHEETNAME1 ) {
var selectedCell = ss.getActiveCell();
//checks the column to ensure it is on the one we want to cause the date and calculations to appear.
if( selectedCell.getColumn() == COLUMNTOCHECK) {
var dateTimeCell = selectedCell.offset(DATETIMELOCATION[0],DATETIMELOCATION[1]);
dateTimeCell.setValue(new Date());
var partnerOneCell = selectedCell.offset(PARTNERONELOCATION[0],PARTNERONELOCATION[1]);
partnerOneCell.setValue((partnerOnePercent/100)*partnerOnePaySource);
var partnerTwoCell = selectedCell.offset(PARTNERTWOLOCATION[0],PARTNERTWOLOCATION[1]);
partnerTwoCell.setValue((partnerTwoPercent/100)*partnerTwoPaySource);
var partnerThreeCell = selectedCell.offset(PARTNERTHREELOCATION[0],PARTNERTHREELOCATION[1]);
partnerThreeCell.setValue((partnerThreePercent/100)*partnerThreePaySource);
}
}
}
The thing I would like it to do is when I enter a payment into the column (column 13), Is for the payment to be split into the partner location cells (var partnerOneCell, var partnerTwoCell, var partnerThreeCell) that are offset from the cell that the payment amount is typed in, and I only want it to be calculated by the percentages as they are at the moment the payment amount is entered. Any help would be appreciated.
Right now it is only calculating based upon cell M2 (row 2, column 13). I want it to be able to calculate based upon the amount I enter in any cell within that column, and only the cell I am currently updating. I think that this has something to do with getActiveRange or something, but I'm not familiar enough with these methods.
Edit: Upon testing, it also seems that row 3 column 14 is reflecting a calculation of partnerOnePaySource*partnerOnePercent with PaySource coming from row 3 column 13 (M3), though I'm not sure why.
Alright everyone, after reading over my code, I realized how I could use the getActiveCell method within the PaySource variables.
var partnerOnePercent = sheet.getRange("G2").getValue();
var partnerOnePaySource = ss.getActiveCell().getValue();
var partnerTwoPercent = sheet.getRange("G3").getValue();
var partnerTwoPaySource = ss.getActiveCell().getValue();
var partnerThreePercent = sheet.getRange("G4").getValue();
var partnerThreePaySource = ss.getActiveCell().getValue();
With this I was able to fix my problem and it now works.

Paste data starting in column P of google sheets (via script)?

I'm trying to post an array into column P daily. Because it's posting daily, I'd like it to also grab the last row.
I'm pulling from another workbook but don't know how to get the paste to work.
Function () {
var toCopy = [copies data from spreadsheet 1]
/* trying to paste into Aggregate tab in spreadsheet 2*/
var ss2=SpreadsheetApp.openById(‘spreadsheet 2’);
var tsh2=ss2.getSheetByName('Aggregate');
var tsh2.getLastRow(???
}
How do I paste var toCopy into column P? The array is 15 columns wide.
You want to append the values to the next row of the last row of column "P" in the sheet of "Aggregate".
The values are 2 dimensional array which has 600 rows and 15 columns.
The number of rows is changed every run.
The number of columns is not changed.
After the values are put, you want to retrieve the last row number.
I could understand like above. If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Flow:
Retrieve the last row number of the column "P".
From your question, I'm not sure whether the last row of the column "P" is the last row of the sheet. So the last row is checked for only column "P".
Append "toCopy" to the next row of the last row of column "P".
Retrieve the current last row number.
Modified script:
Please set the values of toCopy and the Spreadsheet ID.
function myFunction() {
var toCopy = [copies data from spreadsheet 1]
var ss = SpreadsheetApp.openById('###');
var sheet = ss.getSheetByName('Aggregate');
// Retrieve the last row of the column "P".
var lastRowOfColP = 0;
var valuesOfColP = sheet.getRange("P1:P").getValues();
for (var i = valuesOfColP.length - 1; i >= 0; i--) {
if (valuesOfColP[i][0]) {
lastRowOfColP = i + 1;
break;
}
}
// Put "toCopy" to the next row of the last row of column "P".
sheet.getRange(lastRowOfColP + 1, 16, toCopy.length, toCopy[0].length).setValues(toCopy);
// Retrieve the current last row number.
var currentLastRow = lastRowOfColP + toCopy.length;
Logger.log(currentLastRow)
}
This modified script supposes that toCopy is 2 dimensional array.
References:
setValues(values)
getRange(a1Notation)
getRange(row, column, numRows, numColumns)
Looks like Set a range's values is what you're after.
function () {
var values = [
// Copied data from spreadsheet 1
]
// Paste into Aggregate tab in spreadsheet 2
var ss2 = SpreadsheetApp.openById(‘spreadsheet 2’);
var sheet2 = ss2.getSheetByName('Aggregate');
var range = sheet2.getRange('P1:P15');
range.setValues(values);
// Grab last row
var lastRow = sheet2.getLastRow();
}
PS: Watch out for the formatting in your code. It looks like you might not be using a proper text editor. Your formatting made function be Function and the quotations 'spreadsheet 2' become ‘spreadsheet 2’. I use VS Code and Vim, for example.

Array size issue when copying GoogleSheet to another sheet

I need to get a sheet of data as an array, perform some processing, then save it to another sheet.
Without attempting any intermediate processing,
var booking = getRowsData(sheet); //should create the array
var range = target.getRange(lastDBRow+1,1,numRows); //obtains the destination range (numRows logged as 3)
then
range.setValues([booking]); //tries to save the values but throws an error "Incorrect range height, was 1 but should be 3"
Checking the booking object with
var response = ui.prompt(booking.length + " " + booking[0].length, ui.ButtonSet.OK);
shows length 3 and
booking[0].length (which I understood to be the columns) as undefined....
So why the row length mismatch?
And should the columns value be undefined?
My thanks in advance!
The full code is :
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('New booking');
var headers = sheet.getRange(1, 1,1,sheet.getLastColumn());
var lastRow = sheet.getLastRow();
var numRows= lastRow-1
var target = ss.getSheetByName('Test'); //temp redirect to test sheet
var lastDBRow =target.getLastRow(); //we want to append the data after this
var booking = getRowsData(sheet); // Get data to copy as array object
= ui.prompt(booking.length + " " + booking[0].length, ui.ButtonSet.OK);
// Returns 3 Undefined
var response = ui.prompt(numRows, ui.ButtonSet.OK);
// Returns 3
var range = target.getRange(lastDBRow+1,1,numRows); // Must match range size
range.setValues([booking]);
}
Looks to me like there is no column count defined in this range:
var range = target.getRange(lastDBRow+1,1,numRows); // Must match range size
range.setValues([booking]);
Without being about to use debug, I can't confirm my idea, but I see you are defining the starting row, the starting column and the number of rows, but not the number of columns. I don't know for sure if that error message would be caused by that, but it looks like something to consider.

Only get non-filtered values for Google App Script getRange

Is there a way to only get non-filtered values only in Google App Script? (i.e. get values that are showing and not hidden ones?
For example, let’s say I have the following cells + values in Google Sheets.
A1=abc B1=x
A2=def B2=y
A3=ghi B3=y
A4=kjl B4=x
And I filtered B column so it only displays [y].
A2=def B2=y
A2=ghi B3=y
When I use the following script, both hidden and non-hidden values gets printed to the msgBox.
function msgBoxTest(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lastColumn = ss.getLastColumn();
var range_input = ss.getRange("A1:A").getValues();
var result = [i for each (i in range_input)if (isNaN(i))];
// remove commas originating from empty cells
Browser.msgBox(result);
//I want only def & ghi to display here.
//Instead, I get all values -> abc,def,ghi,kjl
}
I've googled and looked online but couldn't find code about filtering out values in Google App script. Any suggestions?
If you want to to use script, this will do it:
function msgBoxTest(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lastColumn = ss.getLastColumn();
var range = ss.getRange("A1:B").getValues();
var filter=[]//new array
for(var i=0;i<range.length;i++){
if (range[i][1]=="y"){
filter.push(range[i][0])
}}
Browser.msgBox(filter);
//I want only def & ghi to display here.
}
Or you could do it with a simple query formula:
=query(A1:B,"Select A where B='y'")

Categories