How to make a dynamic source for .getRange() in Apps Script? - javascript

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.

Related

Document variables not recognized by fields. Acrobat Pro

I hope this is the right place for this question. I have been trying to set up a simple document that calculates fields based on other fields with the same document. I am attempting to create a list of variables to make scripting faster. right now my document script looks like this
var lv = this.getField("Level").value;
var s = this.getField("StrB").value;
var d = this.getField("DexB").value;
var c = this.getField("ConB").value;
var int = this.getField("IntB").value;
var w = this.getField("WisB").value;
var ch = this.getField("ChaB").value;
var ss = this.getField("Str").value;
var ds = this.getField("Dex").value;
var cs = this.getField("Con").value;
var ints = this.getField("Int").value;
and so on.
This is an example of a script using these variables
{
event.value = strBonus + pb;
}
This returns nothing. Not even a warning. I double-checked my spelling and names. I am sure this is a formatting issue as I am a novice and don't fully understand the language. Any help would be greatly appreciated! Thank you for your time in reading this.
When you define and initialise a variable in a document level script, they get the field value at that time (and that's normally blank).
So, in order to simplify things, define the variables as Field Objects, such as in
var lv = this.getField("Level") ;
In the calculation, you will then retrieve the field value as, for example, in
var lv1 = lv.value * 5 ;
And that should do it.
About documentation: You will need the Acrobat JavaScript documentation, which is part of the Acrobat SDK documentation, downloadable from the developer section of the Adobe website.

I used js to create my command syntax, now how can I use it?

I have a Google Sheet with .gs script that is successfully generating dynamicnewRichTextValue() parameters which are meant to be injected into a Sheet cell that will contain multiple lines of text each with their own URL. I do not know all of the parameters in advance (might be one text and one link, or two each, or more) which is why I am dynamically generating the parameters.
Let's say the end-state should be this (in this case there are only two line items, but there could be more or less:
var RichTextValue=SpreadsheetApp.newRichTextValue()
.setText("mailto:fred#abcdef.com,mailto:jim#abcdef.com")
.setLinkUrl(0,6,"mailto:fred#abcdef.com")
.setLinkUrl(7,19,"mailto:jim#abcdef.com")
.build();
In my script I don't know how many "setText" parameters or "setLinkUrl" statements I will need to generate, so I am doing it dynamically.
This is simple to handle for "setText" because I can just pass a single variable constructed during an earlier loop that builds the "setText" parameters. Let's call that variable setTextContent, and it works like this:
var RichTextValue=SpreadsheetApp.newRichTextValue()
.setText(setTextContent)
So up to this point, everything is great. The problem is that I have another variable that generates the URL portion of the newrichtextvalue() parameters up to the ".build();" statement. So let's call that variable setUrlContent and it is built in an earlier loop and contains the string for the rest of the statement:
.setLinkURL(0,22,"mailto:fred#abcdef.com").setLinkURL(23,44,"mailto:jim#abcdef.com")
I am stumped trying to figure out how to attach it to the earlier bit. I feel like this is something simple I am forgetting. But I can't find it after much research. How do I hook up setUrlContent to the code above so that the command executes? I want to attach the bits above and get back to assigning it all to a variable I can put into a cell:
var emailCell=SpreadsheetApp.newRichTextValue()
.setText("mailto:fred#abcdef.com,mailto:jim#abcdef.com") // I can dynamically create up to here
.setLinkUrl(0,6,"mailto:fred#abcdef.com") // ...but these last couple lines are
.setLinkUrl(7,19,"mailto:jim#abcdef.com") // stuck in a string variable.
.build();
sheet.getRange(1,1,1,1).setRichTextValue(emailCell)
Thanks!
I believe your goal and situation as follows.
You want to use your script by dynamically changing the number of emails.
Modification points:
When your following script is run, I think that the links are reflected to mailto and fred#abcdef..
var emailCell=SpreadsheetApp.newRichTextValue()
.setText("mailto:fred#abcdef.com,mailto:jim#abcdef.com")
.setLinkUrl(0,6,"mailto:fred#abcdef.com")
.setLinkUrl(7,19,"mailto:jim#abcdef.com")
.build();
sheet.getRange(1,1,1,1).setRichTextValue(emailCell)
I thought that you might have wanted the linked email addresses like below.
fred#abcdef.com has the link of mailto:fred#abcdef.com.
jim#abcdef.com has the link of mailto:jim#abcdef.com.
In this answer, I would like to propose the modified script for above direction.
Modified script:
var inputText = "mailto:fred#abcdef.com,mailto:jim#abcdef.com"; // This is your sample text value.
var ar = inputText.split(",").map(e => {
var v = e.trim();
return [v.split(":")[1], v];
});
var text = ar.map(([e]) => e).join(",");
var emailCell = SpreadsheetApp.newRichTextValue().setText(text);
var start = 0;
ar.forEach(([t, u], i) => {
var len = t.length;
emailCell.setLinkUrl(start, start + len, u);
start += len + 1;
});
SpreadsheetApp.getActiveSheet().getRange(1,1,1,1).setRichTextValue(emailCell.build());
In this modification, inputText is splitted to the hyperlink and the text (for example, when your sample value is used, it's fred#abcdef.com and mailto:fred#abcdef.com.), and the text including the hyperlink are put to the cell.
In this case, for example, even when var inputText = "mailto:fred#abcdef.com,mailto:jim#abcdef.com" is modified to var inputText = "mailto:fred#abcdef.com" and var inputText = "mailto:fred#abcdef.com,mailto:jim#abcdef.com,mailto:sample#abcdef.com", each hyperlink are reflected to each text.
Note:
When you want to the hyperlink of mailto:fred#abcdef.com to the text of mailto:fred#abcdef.com, you can also use the following modified script.
var inputText = "mailto:fred#abcdef.com,mailto:jim#abcdef.com"; // This is your sample text value.
var ar = inputText.split(",").map(e => e.trim());
var emailCell = SpreadsheetApp.newRichTextValue().setText(inputText);
var start = 0;
ar.forEach((t, i) => {
var len = t.length;
emailCell.setLinkUrl(start, start + len, t);
start += len + 1;
});
SpreadsheetApp.getActiveSheet().getRange(1,1,1,1).setRichTextValue(emailCell.build());
References:
newRichTextValue()
Class RichTextValueBuilder
Class RichTextValue

Get random range google spreadsheet

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.

Why does Google Apps Script throw 'ReferenceError: "bold" is not defined' when using .setBold()?

The context: I need to process/correct many text documents containing multiple particular textual errors, highlight keywords in 'bold' and then output the result. I have a Google spreadsheet with two worksheets: one with two columns of 'wrong wordforms' and 'replacement wordforms' (2d array) that I intend to add to over time and use it as a datastore to 'call from;' the other, a single-column collection of words (1d array) I designate "keywords" to check for and then highlight in the target documents.
Things I've tried that worked: I used a basic array iteration loop from a beginner video (I can't add more links yet, I apologize) and swapped in body.replaceText() for the sendEmail(), successfully, to process the corrections from my "datastore" into my target document, which works nearly perfectly. It ignores text values without the exact same case...but that's a problem for another day.
function fixWords() {
// Document to edit
var td = DocumentApp.openById('docId1');
// Document holding comparison datastore
var ss = SpreadsheetApp.openById('docId2');
// Create data objects
var body = td.getBody();
var sheet = ss.getSheetByName("Word Replacements");
var range = sheet.getDataRange();
var values = range.getValues();
// Create a loop (iterate through the cell data)
for (i=1;i<values.length;i++) {
fault = values[i][0];
solution = values[i][2];
body.replaceText(fault, solution);
}
}
Things I've tried that fail: I then tried just swapping out values for setBold() with the replaceText() code, but the closest I got was the first instance of a keyword from the array would be styled correctly, but no further instances of it...unlike ALL of the instances of an incorrectly spelled word being corrected from the Word Replacements array using the fixWords function.
I found the 'highlightTextTwo' example here at stackoverflow which works very well, but I couldn't figure out how to swap in an external data source or force the included different iteration loop to work in my favor.
I've scanned the GAS reference, watched Google developer videos for snippets that might apply...but clearly I'm missing something that's probably basic to programming. But I honestly don't know why this isn't as easy as the body.replaceText() functionality.
function boldKeywords() { // https://stackoverflow.com/questions/12064972
// Document to edit
var doc = DocumentApp.openById('docId1');
// Access the keyword worksheet, create objects
var ss = SpreadsheetApp.openById('docId2');
var sheet = ss.getSheetByName("Keywords");
var range = sheet.getDataRange();
var values = range.getValues();
var highlightStyle = {};
highlightStyle[DocumentApp.Attribute.BOLD] = 'true';
for (i=1; i<values.length; ++i) {
textLocation = values[i];
if (textLocation != null && textLocation.getStartOffset() != -1) {
textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
}
}
}
This throws out 'TypeError: Cannot find function getStartOffset in object DIV. (line 15, file "boldIt").' I guess this means that by just blindly swapping in this code, it's looking in the wrong object...but I cannot figure out why it works for x.replaceText() and not for x.setAttributes() or x.setBold or .getElement().getText().editAsText()...there just doesn't seem to be a "Learn Google Apps Script example" that deals with something this low on a scale of mundane, uninteresting use cases...enough for me to figure out how to direct it to the right object, and then manipulate the "if statement" parameters to get the behavior I need.
My current brick wall: I spotted this example, again, Text formatting for strings in Google Documents from Google Apps Script, and it seemed promising, even though the DocsList syntax has been deprecated (I'm fairly sure). But now I get "bold is not defined" thrown at me. Bold...is not defined. :: mouth agape ::
function boldKeywords() {
// Access the keyword worksheet, create objects
var ss = SpreadsheetApp.openById('docId1');
var sheet = ss.getSheetByName("Keyterms");
var range = sheet.getDataRange();
var values = range.getValues();
// Open target document for editing
var doc = DocumentApp.openById('docId2');
var body = doc.getBody();
// Loop function: find given keyword value from spreadsheet in target document
// and then bold it (highlight with style 'bold')
for (i=1; i<values.length; ++i) {
keyword = values[i];
target = body.findText(keyword);
body.replaceText(target,keyword);
text = body.editAsText();
text.setBold(text.startOffset, text.endOffsetInclusive, bold);
}
}
I will happily sacrifice my firstborn so that your crops may flourish for the coming year in exchange for some insight.
I use this for my scripts, the setStyleAttribute method.
Documentation : https://developers.google.com/apps-script/ui_supportedStyles
Example :
TexBox.setStyleAttribute("fontWeight", "bold");
The bold parameter is a Boolean data type. You need to use the word true or false.
Replace "bold" with "true".
text.setBold(text.startOffset, text.endOffsetInclusive, true);
Check out the "Type" column in the documentation:
Google Documentation - setBold

Google Spreadsheet Determine lowest number in a row of cells

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

Categories

Resources