I have a little knowledge of javascript I just want to know how to make a script that works in these scenario
I just want to set the second-row with D2:F2, or as long as the first row has a value to be a reference in the formula like in cells: D2={franco!F2:F}; E2={justin!F2:F}; F2 ={aeron!F2:F} and so on...
currently I am using the following codes:
function setFormula() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var rangeList = ss.getRange('d1:f1').getValue();
var range = ss.getRange('d2:f2');
range.setValue('={'+rangeList+'!F2:F}');
}
hope that someone can help me with this code. Thank you in advance
You want to put the formulas of {franco!F2:F}, {justin!F2:F} and {aeron!F2:F} to the cells "D2", "E2" and "F2", respectively.
In this case, you want to retrieve the values of franco, justin, aeron from the cells "D1:F1".
You want to achieve this using Google Apps Script.
I could understand like above. For this, how about this answer? Please think of this as just one of several possible answers.
Sample script:
function setFormula() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var rangeList = ss.getRange('d1:f1').getValues()[0];
var range = ss.getRange('d2:f2');
range.setFormulas([rangeList.map(function(e) {return '={'+e+'!F2:F}'})]);
}
At first, the values of franco, justin, aeron are retrieved. Using these values, each formula is creted in the loop with map
setFormulas uses the 2 dimensional array. Please be careful this.
References:
getRange()
getValues()
setFormulas()
map()
Related
Original Question:
I have multiple tabs in a Google Spreadsheet that represent different data sources. Currently, I have a variable (var = quote1location) that is equal to the sheet name that I would like to get my data from based on other logic.
Pretend that quote1location can equal 'Sheet1', 'Sheet2', or 'Sheet3' depending on the logic but for this case, it equals 'Sheet1'.
var totalpeople = quote1location.getRange('A1').getValue();
In the function above, Apps Script will return an error saying 'quote1location.getRange is not a function' because Apps Script is not substituting the value of the variable that I have designated ('Sheet1') but is using the variable name ('quote1location' instead. I would like Apps Script to process this as 'Sheet1.getRange('A1').getValue()'.
Your help would be appreciated
Answer:
Thank you all for your responses. What I was trying to do is use a string in the 'getRange()' function. Pretend I had two Google Sheets named 'Sheet1' and 'Sheet2' and I had a variable that helped me determine what sheet to grab as my data reference. I was trying to set a variable as either (var source = 1) or (var source = 2) so that I could then use this variable in my getRange() function like this: ('Sheet' + source).getRange('A1').getValue();
What I was trying to do here is if var source = 1, then I would get my data from 'Sheet1'. If the var source = 2, then I would get my data from 'Sheet2'.
The issue (as mentioned by those who responded) is that I was trying to use .getRange() on a string, not an object like a specific spreadsheet. Instead of using var source = 2 or var source = 1 I should be using
ss = SpreadSheetApp.getActiveSpreadsheet()
if(somevariable = somecondition){
var source = ss.getSheetbyName('Sheet1')
}
if(someothervariable = someothercondition){
var source = ss.getSheetByName('Sheet2')
}
Now when I use getRange()' on 'source', it will be calling the sheet that I have designated rather than trying to retrieve a range from a string which will not work.
Thank you very much to all who provided feedback.
I believe you are looking to do:
const quote1Location = SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName(`Sheet1`)
const totalPeople = quote1Location.getRange(`A1`).getValue()
Alternatively:
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
const quote1Location = `Sheet1`
const totalPeople = spreadsheet.getSheetByName(quote1Location)
.getRange(`A1`)
.getValue()
Whether these are the exact syntax you're hoping to use or not, I hope this helps you better understand how to accomplish accessing a Sheet.
I want to create DataValidation for a cell in google sheets with google app scripts, but i cannot find the syntax to create a custum formula for the validation.
My idea is to create a code to validate a time format HH:MM. For this matter i already have a a working Regexp (function CheckRegexp)
The only documentation i´ve found so far to this issue is this one: https://developers.google.com/apps-script/reference/spreadsheet/data-validation-criteria
function test() {
var sheet = SpreadsheetApp.getActiveSheet();
var cell = sheet.getRange("E4");
var criteria = SpreadsheetApp.DataValidationCriteria.CUSTOM_FORMULA
//Custom formula CheckRegexp
var dv = SpreadsheetApp.newDataValidation().withCriteria(criteria, args).build();
cell.setDataValidation(dv);
}
function CheckRegexp(input) {
return /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/.test(input);
}
I want the result to be a Data Validation for my Regexp in a desire range.
It's not possible to set a custom formula(script-based) as a data validation criteria. Custom formula in this context(DataValidationCriteria.CUSTOM_FORMULA) refers to custom crafted formula by nesting inbuilt formulas.
Possible solution(s):
Use a edit trigger onEdit(e) to check each edit, whether it satifies a condition and clear the cell e.range.clear(), if not OR
Use inbuilt formula like this:
=REGEXMATCH(TO_TEXT(E4),"^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$")
To Read:
Event Objects
REGEXMATCH
Just another way for data validation is below:
=AND(ISDATE(E4), TEXT(E4, "hh:mm")=TO_TEXT(E4))
REGEXMATCH function is also suitable, but it may appear to be less readable for somebody.
By the way, both cases do not reject incorrect numerical input (I dont know why). They only mark cells as "Invalid: This cell's contents violate its validation rule".
It's too late, but might help someone still looking for it. Here's how you can set Custom Formula validation through script:
var range = SpreadsheetApp.getActive().getRange("A2");
var criteria = SpreadsheetApp.DataValidationCriteria.CUSTOM_FORMULA;
var args = ["=ISNUMBER(A2)"];
var val = SpreadsheetApp.newDataValidation().withCriteria(criteria,args);
val.setAllowInvalid(false);
val.setHelpText("Please enter valid number.");
range.setDataValidation(val);
I have managed with VBA and Excel to achieve my purposes, but I'd like to move to google spreadsheet for particular reasons.
I'm trying to replicate a code that works just fine in VBA.
It's simple, I have a sheet with a bank of questions in column A, and I'd like a macro that can select 1 random question and copy it to a second sheet.
I'm having trouble understanding how I can access a random cell, copy it and paste it to the second sheet. Some plain explanation would be appreciated since I have very little or non-existent knowledge of programming or javascript.
function test() {
var ss = SpreadsheetApp.openById("sheetID");
//Say I have 10 questions in the BANKSHEET, for instance
var rQuestion = Math.floor(Math.random()*10+1);
//What goes in A1? So that I can access the range randomly according to rQuestion value.
var inputRange = ss.getSheetByName("BANKSHEET").getRange("A1");
var inputValues = inputRange.getValues();
var outputRange = ss.getSheetByName("QUIZZ").getRange("A1").setValues(inputValues);
How about this modification? I think that there are several solutions for your situation. So please think of this as one of them.
Modification points :
Retrieve the number of cells at "A1:A" from sheet of "BANKSHEET".
Retrieve randomly one of the number.
Copy the cell value of the retrieved number to "A1" of "QUIZZ".
Modified script :
function test() {
var ss = SpreadsheetApp.openById("sheetID");
// Retrieve randomly a value from sheet of BANKSHEET
var sheet = ss.getSheetByName("BANKSHEET");
var src = sheet.getRange("A" + (1 + Math.floor(Math.random() * sheet.getLastRow())));
// Put the value to "A1" at sheet of QUIZZ
var dst = ss.getSheetByName("QUIZZ").getRange("A1");
src.copyTo(dst);
}
Note :
It supposes that there are values in only column A of "BANKSHEET".
This modified script randomly retrieves one value from column A of "BANKSHEET" every time.
If you don't want to use the value which has already been used, please modify the script for your situation.
Reference :
copyTo()
If I misunderstand your question, I'm sorry.
I've been struggling trying to find a method to place information from a cell (a range of cells) as comments in a different cell (range of cell) in a different sheet.
Something like this, if I have Apple in Cell A1 in Sheet1 I want Apple to be inserted as a comment in Cell F1 in Sheet 2.
I tried coming up with something like this.
//I'm still working on this I have not been able to make this work//
//Ideally this will put the phone numbers as comment's in the needed cases//
var ss = SpreadsheetApp.getActiveSpreadsheet();
var targetsheet = ss.getSheetByName("report");
var sourcesheet = ss.getSheetByName("Sheet1");
var nrange = sourcesheet.getRange(2, 3, sourcesheet.getLastRow(), 1)
var sourcenotes = [nrange.getValue()]
var notes = targetsheet.getRange(2, 6, sourcesheet.getLastRow(),1)
notes.setNotes(sourcenotes);
As you can read this is not working I've tried different methods but none is working so I come to you guys for help.
The function "setNotes" takes a 2 dimension array, the value should be like this setNotes([sourcenotes]). Check the documentation.
Also if you are going to set the note for just one cell, i would recomend to use the function setNote. Here is an example on that function.
I'm new to this site for the main purpose that I plan to pursue a career in programming. I've landed my first job at an engineering company who is asking me to set up a system in which they can easily determine the time between a job being filed, and it's completion. We're using spreadsheet docs right now to accomplish certain pieces of this.
I'm looking to create a custom function in Google Docs that will allow me to traverse the array of values in row C and then compare it with a number that the function was called with, compare the number to the number in the array and give me which one is the smaller number. EDIT: The function will be called on another sheet called "parsed data" located in the same project file. It's purpose is to automatically file the order number of a current project (just for the sake of being organized) All the other functions I plan to implement will be based off of this order number being correct.
So far, I've gathered this much (I'm learning this on the fly because I still lack experience, so bear with me.)
{
/**created by Alexander Bickford for use at Double E Company
*sorts through a range of values to determine the lowest next value
*returns lowest determined value of next cell
*/
//List Of To Be Implemented Functions
// sheet.appendRow
function setValue(num)
{
var ss = SpreadsheetApp.getActiveSpreadsheet('parsed data');
var ss = ss.getSheets()[0];
var myRange = ss.getRange("C:C").getValues();
newValues = [];
for(i=1;i<=myRange;i++) //Loop to traverse the C range and find the lowest value.
{
if(num<=range[3][i])
{
}
else
num = range[3][i];
}
return num;
}
}
when I call the function in the spreadsheet, I'm getting an error passed that says:
error: ReferenceError: "SPREADSHEET_ID_GOES_HERE" is not defined. (line 8, file "Code")
Google predefines some functions at the top that look like this:
/**
* Retrieves all the rows in the active spreadsheet that contain data and logs the
* values for each row.
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_spreadsheet
function readRows() { <---Line 8 in the file
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
Logger.log(row);
}
};
* Adds a custom menu to the active spreadsheet, containing a single menu item
* for invoking the readRows() function specified above.
* The onOpen() function, when defined, is automatically invoked whenever the
* spreadsheet is opened.
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_spreadsheet
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Read Data",
functionName : "readRows"
}];
sheet.addMenu("Script Center Menu", entries);
};
End Code I don't need */
I assume it has something to do with the earlier lines (I pointed out line 8). Any thoughts?
Below code is working fine for me.
var ss = SpreadsheetApp.getActiveSheet();
var myRange = ss.getRange("C:C").getValues();
newValues = [];
for(i=1;i<=myRange.length;i++)
{
Logger.log(myRange[i]);
}
Looking at your code, it seems like you have a few problems.
You seem to be mixing up "sheets" with "spreadsheet", and your redundant declaration of "ss" as a variable is bound to cause you some problems.
You seem to be passing in arguments to the incorrect methods. I had this same problem when working with the Google App script earlier. It took a lot of poking around Google's Documentation (which you should really take a look at: https://developers.google.com/apps-script/). You seem to be making the same mistake I did, coding by analogy. looking at Google's sample code and trying to replicate is bound to bump you into some trouble.
Some useful advice:
The most confusing thing to wrap your head around is the structure: spreadsheet>>sheet>>range, you have to explicitely deal with the one's on top before moving to the one's on the bottom.
Remove the 'parsed data' argument from getActiveSpreadsheet(), it should be blank. What you want to use is "getSheetByName("parsed data")" and pass that into a sheet variable.
In your for loop, you also need to use the ".length" method, or use the ".getLastRow()" method with a sheet object to find the last row in your sheet.
Your code might look something like this:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName("parsed data");
var endRowNumber = sheet1.getLastRow();
//insert rest of code