Here is the sample sheet link
https://docs.google.com/spreadsheets/d/1ijCIzNmlV5V6Y3_PyHIeol7knK_h1FEcmaUPZZ0f5kA/edit?usp=sharing
Column A Contains the different spreadsheet address under my account. in column B i need the Spreadsheet Title of Each Address. Is there any Appscript or Function Available to automate it
You can try this code below, this should be pretty self descriptive:
Code:
function getSpreadsheetNames() {
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
var sheetIds = sheet.getRange("A2:A" + lastRow).getValues();
sheetIds.forEach(function (sheetId, index){
var title = SpreadsheetApp.openById(sheetId).getName();
sheet.getRange(index + 2, 2).setValue(title);
});
}
Output:
Note:
I did my sample on my spreadsheets since I don't have permission on your spreadsheets.
Running this on sheets you don't have access to will cause this error:
In the case above, ask the owner of the sheets to give you access so that the script will run.
Related
I currently use a Google sheet to hold data x1 row per item. I use one particular cell to hold two separate hyperlinks within (x2 website addresses), both links are relevant/in relation to this item.
I want to keep the structure of having two separate clickable hyperlinks in one cell, but I also need to import this cell data (these two links) into another Google sheet, is there a way of using IMPORTRANGE and retaining these two separate hyperlinks (ensuring clickable & still x2 separate links within one cell), or converting them into hyperlinks when importing into another sheet?
Thank you in advance
I've created two dummy sheets with data for testing & to help visualise
Sheet Name: "Static" & Sheet URL: https://docs.google.com/spreadsheets/d/1JS40eNGUAmBqQJqmdX4PhWtm6GEVQP64CoxO_DooZYM/edit#gid=0
Sheet Name: "Imported" & Sheet URL: https://docs.google.com/spreadsheets/d/1rhnULIcbkSMCp8AONa7UwTQz77uHn443VuwYjty2xFs/edit#gid=0
I've used =IMPORTRANGE("1JS40eNGUAmBqQJqmdX4PhWtm6GEVQP64CoxO_DooZYM","Static1!A1:D")
To pull data from 'Static' sheet (tab: 'Static1') into 'Imported' (tab: 'Imported1')
I'm hoping to get clickable links in column 'D' of the 'Imported' sheet
I've added different variations i.e. the hyperlinks are renamed in 'Static' sheet as "Link 1" & "Link 2", I've added a few rows with full URLs addresses (no re-naming), and a couple with full URLs and with an empty line in between - I'm not too fussed with how they look to be honest (ideally it would be nice to have 'Link 1' & 'Link 2') but mainly just looking to have x2 imported URLs within same cell that remain/become clickable after importing
This is because I'll also be iframe/embedding the 'Imported' sheet afterwards.
Thank you
You can extract the urls by a custom function in addition of the IMPORTRANGE
function extractUrls(range) {
var activeRg = SpreadsheetApp.getActiveRange();
var activeSht = SpreadsheetApp.getActiveSheet();
var activeformula = activeRg.getFormula();
var rngAddress = activeformula.match(/\((.*)\)/).pop().trim();
var urls = activeSht
.getRange(rngAddress)
.getRichTextValue()
.getRuns()
.reduce((array, e) => {
var url = e.getLinkUrl();
if (url) array.push(url);
return array;
}, []);
return ([urls])
}
edit
in your situation
function createCopy() {
var id = "1JS40eNGUAmBqQJqmdX4PhWtm6GEVQP64CoxO_DooZYM"
var source = SpreadsheetApp.openById(id).getSheets()[0]
var values = source.getRange(2,1,source.getLastRow()-1,3).getValues()
var richTxt = source.getRange(2,4,source.getLastRow()-1,1).getRichTextValues()
var output = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('output_v2')
output.getRange(2, 1, values.length, values[0].length).setValues(values)
output.getRange(2, 4, richTxt.length, richTxt[0].length).setRichTextValues(richTxt)
}
UPDATE:
Option 1:
This is fairly straightforward. It just copies the Static1 sheet unto a destination sheet and names it Imported.
function createCopy2() {
var ss = SpreadsheetApp.openById("1vM-0nBBlhVvRQ3vvXwkWlecENM7CVuv8iei3cl0uRQI");
var ds = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Static1');
sheet.copyTo(ds).setName('Imported');
}
Option 2 (incomplete):
This is what I have done so far, but this still throws an error Exception: Illegal Argument at this line var text = SpreadsheetApp.newRichTextValue().setText(linkval[i]).setLinkUrl(0,7,urls1[i]).setLinkUrl(7,13,urls2[i]).build();.
(P.S: Just wanted to throw this out here if in case someone would find this logic useful/not to waste my efforts practicing JS lol).
Kudos to Mike Steelson for providing a working answer.
function createCopy() {
//Creates a full copy of the source sheet without Hyperlinks (AKA importrange in script form)
var ss = SpreadsheetApp.openById("1vM-0nBBlhVvRQ3vvXwkWlecENM7CVuv8iei3cl0uRQI");
var sheet = ss.getSheets()[0].getSheetValues(1,1, ss.getLastRow(), ss.getLastColumn());
var ds = SpreadsheetApp.getActiveSheet();
ds.getRange(1,1, ss.getLastRow(), ss.getLastColumn()).setValues(sheet);
Logger.log(sheet);
var link = ds.getRange(2,4, ss.getLastRow(), 1);
var linkval = link.getValues();
var urls1 = ds.getRange(2,5, ss.getLastRow(), 1).getValues();
var urls2 = ds.getRange(2,6, ss.getLastRow(), 1).getValues();
for(i=0; i < ss.getLastRow(); i++){
var text = SpreadsheetApp.newRichTextValue().setText(linkval[i]).setLinkUrl(0,7,urls1[i]).setLinkUrl(7,13,urls2[i]).build();
}
}
I found code to list the names of all the sheets in Google Sheets
function sheetnames() {
var out = new Array()
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets()
for (var i=2 ; i<sheets.length ; i++) out.push( [ sheets[i].getName() ] )
return out
}
But we must place =sheetnames() in a cell to get value.
Is there any improvement in the script to automatically update when creating a new sheet?
You have to install an onChange trigger, which runs a function whenever a user modifies the structure of the spreadsheet—for example, when a sheet is inserted or removed.
You can install the trigger manually, following these steps, or programmatically, executing this function once:
function createOnChangeTrigger() {
const ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger("writeSheetNames")
.forSpreadsheet(ss)
.onChange()
.create();
}
Once this is installed, the function writeSheetNames will run every time a sheet is created, removed, or renamed. This function should do two things:
Retrieve the sheet names of all the sheets in the spreadsheet.
Write these sheet names to the cell you indicate.
For example, the function below would write the data to column A of the sheet named Sheet1.
Code sample:
function writeSheetNames() {
const ss = SpreadsheetApp.getActive();
const sheetNames = ss.getSheets().map(sheet => [sheet.getName()]);
const sheet = ss.getSheetByName("Sheet1");
sheet.getRange("A:A").clear(); // Delete previous data
sheet.getRange(1,1,sheetNames.length).setValues(sheetNames);
}
Reference:
onChange
I am trying to write a formula that counts the number of times the number 1 appears in cell F1 of all my sheets. My sheets have varying names (18-0100, 18-0101, 18-0102...). I tried the following formula:
=COUNTIF(INDIRECT("'"&"'!F1"),"=1")
It acts unpredictably. It will only return 1 even if it should be more than 1. And when I try to start trying to count 2 instead of 1 it returns 0 and not the correct number.
What am I doing wrong?
Your formula counts only the current sheet.
To get them all you need to enter all sheet names:
The formula for each sheet is:
=(INDIRECT("'"& sheet_name &"'!F1")=1)*1
You can leverage a Google Apps Script to pull this off as well.
From your spreadsheet, go to Tools > Script Editor. Add the code below, then save. The function saved there will be accessible by all other Google apps, including your spreadsheet. You can then use the name of the function in your spreadsheet like you would with any other formula.
function OccurrencesInSheetNames(str) {
var c = 0;
var regExp = new RegExp('[' + str + ']', 'g');
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var sheetnames = [];
for (var i=0; i<sheets.length; i++) {
sheetnames.push([sheets[i].getName()]);
}
for (var i=0; i<sheetnames.length; i++) {
var name = sheetnames[i].toString();
var count = (name.match(regExp) || []).length;
c += count;
}
return c;
}
Now in your cell F1, place the following formula:
=OccurrencesInSheetNames(TEXT(1,0))
You can also replace the 1 in the above formula with a cell reference, if that works better for your needs. (e.g. =OccurrencesInSheetNames(TEXT(C5,0)) if you want to search through your sheet names for the integer number found in cell C5.)
Here's a demo spreadsheet for you to try out.
I'm trying to create a dynamic HYPERLINK formula that will automatically create the link based on the sheet name in Column A, but I'm not sure how (or if it's possible) to get the URL of the sheet based on the name.
Here's the setup:
Single Google Spreadsheet with multiple tabs
Tab names: 1500, 1501, 1502, Consolidated
On the Consolidated tab, I have two columns: Column A is the Sheet Name, and Column B is a HYPERLINK formula, that when clicked should open the corresponding sheet.
Is there a way to programmatically get the URL for the sheet based on the sheet name in Column A? Perhaps I could use a script to populate Column C with the URL, then use the following formula: =HYPERLINK(C2,A2)?
Thanks for the help!
Surprised to see this as a top search on Google but with no answer.
Anyway, here's the method I found that works for me: combine Hyperlink with values from a different column using the &, a basic example is shown below:
If you are trying to automatically generate direct URL's to specific sheets based on their name, and do not want to use scripts, you are out of luck. Currently, the only way to link directly to specific sheets is by appending the correct gid number to the spreadsheet URL. A gid must be either copied manually from the active sheet's URL, or automatically extracted with a custom function, created using scripts.
Since you're open to using scripts, it looks like i found a detailed tutorial of how to do this. https://www.benlcollins.com/spreadsheets/index-sheet/
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Index Menu')
.addItem('Create Index', 'createIndex')
.addItem('Update Index', 'updateIndex')
.addToUi();
}
// function to create the index
function createIndex() {
// Get all the different sheet IDs
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var namesArray = sheetNamesIds(sheets);
var indexSheetNames = namesArray[0];
var indexSheetIds = namesArray[1];
// check if sheet called sheet called already exists
// if no index sheet exists, create one
if (ss.getSheetByName('index') == null) {
var indexSheet = ss.insertSheet('Index',0);
}
// if sheet called index does exist, prompt user for a different name or option to
cancel
else {
var indexNewName = Browser.inputBox('The name Index is already being used,
please choose a different name:', 'Please choose another name',
Browser.Buttons.OK_CANCEL);
if (indexNewName != 'cancel') {
var indexSheet = ss.insertSheet(indexNewName,0);
}
else {
Browser.msgBox('No index sheet created');
}
}
// add sheet title, sheet names and hyperlink formulas
if (indexSheet) {
printIndex(indexSheet,indexSheetNames,indexSheetIds);
}
}
// function to update the index, assumes index is the first sheet in the workbook
function updateIndex() {
// Get all the different sheet IDs
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var indexSheet = sheets[0];
var namesArray = sheetNamesIds(sheets);
var indexSheetNames = namesArray[0];
var indexSheetIds = namesArray[1];
printIndex(indexSheet,indexSheetNames,indexSheetIds);
}
// function to print out the index
function printIndex(sheet,names,formulas) {
sheet.clearContents();
sheet.getRange(1,1).setValue('Workbook Index').setFontWeight('bold');
sheet.getRange(3,1,names.length,1).setValues(names);
sheet.getRange(3,2,formulas.length,1).setFormulas(formulas);
}
// function to create array of sheet names and sheet ids
function sheetNamesIds(sheets) {
var indexSheetNames = [];
var indexSheetIds = [];
// create array of sheet names and sheet gids
sheets.forEach(function(sheet){
indexSheetNames.push([sheet.getSheetName()]);
indexSheetIds.push(['=hyperlink("#gid='
+ sheet.getSheetId()
+ '","'
+ sheet.getSheetName()
+ '")']);
});
return [indexSheetNames, indexSheetIds];
}
Please help.
I want more frequent updates so I want to use gscripts.
I need to retrieve the value of this source:
Filename: Peta Finance
Name Sheet: Data
Key: xxx111xxx
Cell: B15
Target is:
Filename: Finance
Name Sheet: Data1
Key: xxx222xxx
Cell: A2
I try this code, except that they are not working:
function importData() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); //source ss
var sheet = ss.getSheetByName("Finance Peta"); //opens the sheet with your source data
var values = sheet.getRange("C1").getValues(); //gets needed values
var ts = SpreadsheetApp.openById("xxx"); //target ss - paste your key
ts.getSheetByName("Finance").getRange("B15").setValues(values);
}
Funnily enough I asked something similar the other day. My code, edited to match yours is as follows:
function importData() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data1 Key");
var update = 'IMPORTRANGE("XXX","Data Key!B15"); //"XXX" is the spreadsheet key of your source [Peta Finance]
sheet.clear(); //Be careful with this. It clears the whole sheet including formatting. This part might need playing around a bit with
sheet.getRange("A2").setValue(update);
Utilities.sleep(245); //This just gives the set number of milliseconds before it carries out it's next process (not necessarily required if this is only action)
};
I then created a menu which allows me to manually refresh the data, or cell in your case. This is as follows in the same script file:
function onOpen(){
var spreadsheet = SpreadsheetApp.getActive();
var menuItems = [
{name: 'Import Data', functionName: 'importData'}
];
spreadsheet.addMenu('Import', menuItems);
}
You can then add timed triggers to set it to update, although importrange should automatically do it.
To do this click on Resources >> Current Project's Triggers >> set one up >>
Make it as follows >> Run: importData Events: Time-driven >> select the time between updates.