I am trying to build a complex string to insert a new formulae on the fly in google script. In VBA you use chr(34), is there a similar work around in google script?
Thanks
From this thread "Some common VBA functions translated to Google Apps Script" you will find here in Slide 6 that the function Chr(n) in VBA is translated in the javascript:
function Chr(n) {
return String.fromCharCode(n);
}
You can also find it in this Github.
For the sample code on how to use this function in AppsScript, check this link.
var map = Maps.newStaticMap();
for (var i = 0; i < route.legs.length; i++) {
var leg = route.legs[i];
if (i == 0) {
// Add a marker for the start location of the first leg only.
map.setMarkerStyle(markerSize, markerColor, String.fromCharCode(markerLetterCode));
map.addMarker(leg.start_location.lat, leg.start_location.lng);
markerLetterCode++;
}
map.setMarkerStyle(markerSize, markerColor, String.fromCharCode(markerLetterCode));
map.addMarker(leg.end_location.lat, leg.end_location.lng);
markerLetterCode++;
}
Related
I already have code that works, but the formatting is not preserved. When executing the function, a pop-up window is displayed, the words can be entered here. When the script has run through, the words are replaced but the formatting of the file is completely broken. I think it's because of getParagraphs. Does anyone know an alternative?
CODE:
function anpassen(){
var varMap={};
var file=DriveApp.getFileById(DocumentApp.getActiveDocument().getId());
var doc= DocumentApp.openById(file.getId());
var para= doc.getBody().getParagraphs();
for(var i=0; i<para.length;i++){
var text=para[i].getText();
if (!text) continue;
text=text.replace(/{{([^}]*)}}/g, function(m, $1) {
if(!varMap[$1]){varMap[$1]= DocumentApp.getUi().prompt($1+"?").getResponseText();
}
return varMap[$1];
});
para[i].setText(text);
}
}
Use Advanced Google Services
As specified in the documentation you can use Document API directly by using Google Apps Script, keep in mind that you'll need to import this Advanced Service like the following:
what's more there's an example of how to handle the style while adding a new text.
Some time ago, Google Sheets changed the adding of links to rich text, and now links cannot be found at the formula anymore. Personally I dislike this change very much because I use a custom function that extracts hyperlinks from cells with the old formula, and with the new change I just cannot find a way of doing this. I am not very good with functions yet, mainly the reason why I wrote my question title as detailed as possible.
What I need to do is to extract hyperlinks from cells using a custom formula, since it will need to be used among many other vanilla formulas. How can I set up a custom function/formula to extract the new hyperlinks based on range?
Here are the sheets where I want to extract links:
https://docs.google.com/spreadsheets/d/1JnSKQ7nd4J3NPRH4uSsOCYms-DF16j1pkCAuJeikToo/edit#gid=317867416
I would like to extract links from the games that are being posted, because I need to use those links elsewhere and I'd also like to have them ready to be imported if ever needed.
I need to specify a formula in another cell which will extract those links. For example =GETURL(B6) which would extract the new rich text hyperlinks based on a range that I insert for it.
Alternatively, is it possible to configure the document so that it makes links in the old format whenever inserted? This way I could try to workaround the new settings and future inserted links would go into the =HYPERLINK formula instead.
Many thanks!
I think this script would come in handy.
It gives the possibility to retrieve back the URL from a hyperlink formula.
Go to script editor, and create a new project.
Save the file.
Head up to Run > linkURL to run the script. This will create a new function in Sheets.
Let’s say cell A1 has the hyperlink in it. Go to any cell and type =linkURL(A1), and then hit Enter.
function linkURL(reference) {
var sheet = SpreadsheetApp.getActiveSheet();
var formula = SpreadsheetApp.getActiveRange().getFormula();
var args = formula.match(/=w+((.*))/i);
try {
var range = sheet.getRange(args[1]);
}
catch(e) {
throw new Error(args[1] + ' is not a valid range');
}
var formulas = range.getFormulas();
var output = [];
for (var i = 0; i < formulas.length; i++) {
var row = [];
for (var j = 0; j < formulas[0].length; j++) {
var url = formulas[i][j].match(/=hyperlink("([^"]+)"/i);
row.push(url ? url[1] : '');
}
output.push(row);
}
return output
}
I am trying to run a google spreadsheet macro (macro.gs) that has to download a huge number of google site links belonging to a domain, but it takes a long time to execute, so the script ends and it is not yet done. I have read that this is designed to be like that (time limited execution), so there's not much I can do there.
function listSites() {
var domain="domain";
var PAGE_LENGTH=200;
sheet = SpreadsheetApp.getActiveSheet();
var sites = SitesApp.getAllSites(domain,0,PAGE_LENGTH);
for(var i=0; sites.length != 0; i+=PAGE_LENGTH){
for (var j=0; j<sites.length; j++) {
sheet.appendRow([sites[j].getUrl()]);
}
sites = SitesApp.getAllSites(domain, i, PAGE_LENGTH);
}
};
However, I have also read that I can try to run a "Task Queue" with Google Apps Script to run it without time limits, but I am not sure if I can run a spreadsheet macro inside a task to evade that time limit.
So far all that I've read does not give any information about how to do it.
Appending a row is really only appropriate if your sheet is volatile, e.g. you can not be certain that new data was added in between the time you calculate the last row and the time you add your new data.
The alternative is to build your output and then serialize it in a single write, usingsetValues with a rectangular 2d Array:
function writeAllSiteUrls() {
const domain = "domain",
PAGE_LENGTH = 200,
output = [];
var i = 0;
do {
var search = SitesApp.getAllSites(domain, i * PAGE_LENGTH, PAGE_LENGTH);
var urls = search.map(function (site) {
return site.getUrl();
});
Array.prototype.push.apply(output, urls);
++i;
} while (search.length);
if (!output.length)
return;
const sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(sheet.getLastRow() +1, 1, output.length, output[0].length).setValues(output);
}
You could certainly build a more complex return object rather than just the site URL, but that wasn't really your question. Also note that any Apps Script code dealing with Google Sites deals with only the "old" version of Google Sites - those made with the new version are not accessible:
A rebuilt version of Sites was launched on November 22, 2016. Apps Script cannot currently access or modify Sites made with this version, but script can still access classic Sites.
References
Array.prototype.push.apply
Array#map
Range#setValues
Google Sites: Old vs. New
I am writing a Google Apps Script to be embedded into Google Sites to retrieve the names and URLs for child pages of the current page. When I call the getURL() function I am getting the following error:
'TypeError: Cannot find function getURL in object WebPage.'
My code is as follows:
function doGet() {
var app = UiApp.createApplication();
var pages = SitesApp.getActivePage().getChildren();
for (var i = 0; i < pages.length; i++) {
Logger.log(pages[i].getURL());
}
return app;
}
I am new to Google Apps Scripts so am struggling to work out what this means. Any help would be greatly appreciated.
Use pages[i].getUrl()
You should use the autocomplete feature in the script editor to avoid such typing errors (control space after the dot : page[i].here type CTRL space and you'll see all possible methods...)
Note : the general rule in javascript is to use the so called camelCase format : getRange, createLabel ... there are only a few exceptions like setHTML but every rule must have exceptions doesn't it ?
i use directionFinder in Google Apps Script application and I want do add some waypoints. Everything works well when i add this like this:
var directions = Maps.newDirectionFinder().setOrigin(start).setDestination(end)
.addWaypoint('Berlin')
.addWaypoint('Hamburg')
.getDirections();
but when I want do add some waypoints dynamicaly in loop like this:
var directions = Maps.newDirectionFinder().setOrigin(start).setDestination(end)
while (results.hasNext()) {
directions.addWaypoint('Berlin')
directions.addWaypoint('Hamm')
}
directions.getDirections();
finally the object directions hasn't any waypoints. What I'm doing wrong? There isn't possible to add waypoints in a loop?
I created a simple script (see bellow). It works correctly - the res contains 4 legs.
function testMapWayPoints() {
var directions = Maps.newDirectionFinder().setOrigin('Berlin').setDestination('Rotterdam');
var wayPoints = ['Potsdam', 'Hanover', 'Dortmund'];
for (var i = 0; i < wayPoints.length; i++) {
directions.addWaypoint(wayPoints[i]);
}
var res = directions.getDirections();
}
I assume that the results.hasNext() returns false. If not then, could you create a minimum compilable example/function which is possible to copy-and-paste to the editor and which reproduces the problem.
Update 00: Additionally I wrote a deployed web app demonstrating that the addWaypoint function works. Here is the app source code.