This question already has answers here:
onEdit() trigger is unable to create a new Spreadsheet
(1 answer)
Google Sheets OnEdit() - You do not have permission to call a service
(2 answers)
Closed 7 months ago.
I write a script and it works fine if you run them separately from app script (RUN bottom). If I run it combined with the "run" bottom in app script it is working, when a enable the checkbox in the sheet, it is not working at all, clearall() is always working, addrecord() is working if I put it before var checkexist = ... , the other 2 are not working (running).
What is wrong here?
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("KLANTinput");
var checkadd = sheet.getRange("AI3").getValue();
if (checkadd === 1) {
var checkexist = sheet.getRange("X2").getValue();
if (checkexist === 0) {
addContactPhoneAndCreateFolder();
Utilities.sleep(500);
createNewFolderInGoogleDrive();
Utilities.sleep(500);
}
addrecord();
Utilities.sleep(500);
clearall();
var checkstate = sheet.getRange("AH3");
checkstate.setValue("FALSE");
}
}
function addContactPhoneAndCreateFolder() {
var sheet = SpreadsheetApp.getActiveSheet();
//var sheet = ss.getSheetByName("KLANTinput");
var first_name = sheet.getRange("J5").getValue();
var last_name = sheet.getRange("AD5").getValue();
var email = sheet.getRange("J15").getValue();
var adres = sheet.getRange("J7").getValue().concat(" ").concat(sheet.getRange("Z7").getValue()).concat(" ").concat(sheet.getRange("J9").getValue()).concat(" ").concat(sheet.getRange("AD9").getValue());
var phone = sheet.getRange("J13").getValue();
Logger.log(adres);
var contact = ContactsApp.createContact(first_name, last_name, email);
var group = ContactsApp.getContactGroup("System Group: My Contacts");
group.addContact(ContactsApp.createContact(first_name, last_name, email));
var contact = ContactsApp.findByEmailAddress(email);
contact.setHomeAddress(adres);
contact.setPrimaryEmail(email);
//contact.setWorkAddress(adres);
contact.setHomePhone(phone);
}
function createNewFolderInGoogleDrive() {
var sheet = SpreadsheetApp.getActiveSheet();
//var sheet = ss.getSheetByName("KLANTinput");
var folderName = sheet.getRange("J5").getValue().concat(" ").concat(sheet.getRange("AD5").getValue()).concat(" ").concat(sheet.getRange("J9").getValue()).concat(" ").concat(sheet.getRange("AD9").getValue()).concat(" ").concat(sheet.getRange("AD19").getValue());
var folder = DriveApp.getFolderById("sheetID");
//Logger.log(folderName);
var nfolder = folder.createFolder(folderName);
}
function addrecord() {
var sss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = sss.getSheetByName("KLANTinput");
var datasheet = sss.getSheetByName("KLANTpredb");
var values = [[sheet.getRange("C2").getValue(), //DATE + TIME
sheet.getRange("J3").getValue(), //DATE
sheet.getRange("K2").getValue(), //DD
sheet.getRange("N2").getValue(), //MM
sheet.getRange("Q2").getValue(), //YY
....
Logger.log(values)
//var roow = datasheet.getLastRow()
//Logger.log(roow)
datasheet.getRange(datasheet.getLastRow() + 1, 1, 1, 45).setValues(values);
}
Related
I have 10 to 15 Files in the Drive Folder All files have more than 1 Google sheets in it with some sort of Conditional Formatting.
I want to copy the Specific Sheet Named "MasterSheet" from each File and Combine the data into the Active Sheet where from script is bieng run.
Copied data should keep conditional formatting cell color. I will appreciate the help. Thanks
function myFunction()
{
var myFolder = DriveApp.getFolderById("FolderID");
var spreadSheets = myFolder.getFilesByType("application/vnd.google-apps.spreadsheet");
var ActiveSpreadSheet = SpreadsheetApp.getActive().getSheetByName(Sheet1);
while(spreadSheets.hasNext())
{
var sheet = spreadSheets.next();
var spreadSheet = SpreadsheetApp.openById(sheet.getId());
for(var y in spreadSheet.getSheets())
{
spreadSheet.getSheets()[y].copyTo(ActiveSpreadSheet);
}
}
}
UPDATE to check if there's a sheet called that way:
function copywithLog()
{
var destinsheet = SpreadsheetApp.getActiveSpreadsheet()
var myFolder = DriveApp.getFolderById("16CxTO70ipcUt8U_beokid3vFOOLGTnPh");
var spreadSheets = myFolder.getFilesByType("application/vnd.google-apps.spreadsheet");
var activeSpreadSheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
var i = 1
while(spreadSheets.hasNext())
{
var sheet = spreadSheets.next();
var spreadSheet = SpreadsheetApp.openById(sheet.getId());
var sheets = spreadSheet.getSheets()
var filtered = sheets.filter(n => ["DATA"].lastIndexOf(n.getSheetName()) == 0)
if (filtered.length==1){
var newsheet = spreadSheet.getSheetByName('DATA').copyTo(destinsheet)
newsheet.getDataRange().copyTo(activeSpreadSheet.getRange(activeSpreadSheet.getLastRow()+2,1))
destinsheet.deleteSheet(newsheet)
Logger.log("Process successfully finished with the workbook named '"+spreadSheet.getName()+"'")}
else Logger.log("The worbook named '"+spreadSheet.getName()+ "' does not have a sheet called DATA")
}
}
It returns something like this:
UPDATE:
function copyinsamesheet()
{
var destinsheet = SpreadsheetApp.getActiveSpreadsheet()
var myFolder = DriveApp.getFolderById("FolderID");
var spreadSheets = myFolder.getFilesByType("application/vnd.google-apps.spreadsheet");
var activeSpreadSheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
var i = 1
while(spreadSheets.hasNext())
{
var sheet = spreadSheets.next();
var spreadSheet = SpreadsheetApp.openById(sheet.getId());
var newsheet = spreadSheet.getSheetByName('MasterSheet').copyTo(destinsheet)
newsheet.getDataRange().copyTo(activeSpreadSheet.getRange(activeSpreadSheet.getLastRow()+2,1))
destinsheet.deleteSheet(newsheet)
}
}
If it has always the same name, you can try with this:
function copyMasterSheets()
{
var destinsheet = SpreadsheetApp.getActiveSpreadsheet()
var myFolder = DriveApp.getFolderById("FolderID");
var spreadSheets = myFolder.getFilesByType("application/vnd.google-apps.spreadsheet");
var ActiveSpreadSheet = SpreadsheetApp.getActive().getSheetByName(Sheet1);
var i = 1
while(spreadSheets.hasNext())
{
var sheet = spreadSheets.next();
var spreadSheet = SpreadsheetApp.openById(sheet.getId());
spreadSheet.getSheetByName('MasterSheet').copyTo(destinsheet).setName('MasterSheet '+i)
i++
}
}
An addendum to the answer by #Martin.
This takes the data on the various "Master Sheets" and copies it to a single sheet.
The range of data on each sheet is established dynamically, and is stacked down the page.
function copyMasters(){
var ss = SpreadsheetApp.getActiveSpreadsheet()
var target = ss.getSheetByName('Sheet1')
// idetify the starting row
var activeStartRow = 1
// get an array of all the sheets with names like "MasterSheet"
var sheetList = new Array
var sheets = ss.getSheets()
//var sourcesheet = ss.getSheets().find(sheet => sheet.getName().includes("MasterSheet"))
var mastersheets = sheets.filter(sheet => sheet.getName().includes("MasterSheet"))
//loop through the Master sheets
for (var i=0;i<mastersheets.length;i++){
var mastername = mastersheets[i].getName()
var master = ss.getSheetByName(mastername)
var masterLC = master.getLastColumn()
var masterLR = master.getLastRow()
// calculate the start row for the target sheet
if (activeStartRow==1){
var startRow =1
}else{
var startRow=startRow+masterLR
}
activeStartRow = 0
var rangeToCopy = master.getRange(1, 1, masterLR,masterLC)
//Logger.log("DEBUG: range to copy:"+rangeToCopy.getA1Notation())
var targetRange = target.getRange(startRow, 1, masterLR,masterLC)
//Logger.log("DEBUG: target range:"+targetRange.getA1Notation())
rangeToCopy.copyTo(targetRange)
// Logger.log("DEBUG: copied the data for "+mastername)
}
}
SAMPLE
This question already has answers here:
GAS "On edit" trigger not running when edited from API
(2 answers)
Installable OnEdit not being called in Stock spreadsheet
(1 answer)
Closed 10 months ago.
I wrote a script that is supposed to automatically send a list from a google sheet via email when the value of cell E7 is above 1.
It works if I change the value of E7 manually.
But when the data is transfered into the google sheet via an external application, it doesn't work. (I already set up a trigger)
What an I doing wrong? Can anyone help me with this?
function FunzioneFE(e) {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Foglio2");
var Cella = sheet.getRange("E7").getValue();
{
if(Cella > 1){
{
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio2").getRange("C2");
var emailAddress = emailRange.getValue();
var Text = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio2").getRange("D2");
var typ = Text.getValue();
var aliases = GmailApp.getAliases();
Logger.log(aliases)
var ws = ss.getSheetByName("Foglio2");
var h1 = ws.getRange("D2").getValue();
var headers = ws.getRange("A1:B1").getValues();
var descr = "FoodEngel"; //headers[0][0];
const tipo = headers[0][1];
var lr = ws.getLastRow();
var tableRangeValues = ws.getRange(2,1,lr-1,2).getValues();
var htmlTemplate = HtmlService.createTemplateFromFile("email");
var file = SpreadsheetApp.getActive();
var sheet = file.getSheetByName("Foglio2");
htmlTemplate.h1 = h1;
htmlTemplate.descr = descr;
htmlTemplate.tipo = tipo;
htmlTemplate.tableRangeValues = tableRangeValues;
var htmlForEmail = htmlTemplate.evaluate().getContent();
console.log(htmlForEmail);
GmailApp.sendEmail(
emailAddress,
typ,
'Bitte Lesen.',{
htmlBody: htmlForEmail,
name: "FoodEngel",
from: aliases[0]
})};
}}}
I'm brand new to Google Apps Script, and I'm trying to create a simple spreadsheet that will allow me to share files by user email through a single spreadsheet.
I have written the following script, which will allow me to add editors and viewers, but not commenters.
I keep getting an error that states that the function addCommenter cannot be found in object spreadsheet.
function shareSheet () {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.toast('Updating access level...');
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var range1 = sheet.getRange (3,1, lastRow,9);
var data = range1.getValues();
for (var i= 0; i < data.length; i++) {
var row = data [i];
var accessLevel = row [5];
var values = row [8];
var ss2 = SpreadsheetApp.openById(values);
var values2 = row [4];
// Add new editor
if (accessLevel == 'Edit') {
var addEditors = ss2.addEditor(values2);
}
// Add new viewer
if (accessLevel == 'View'){
var addViewers = ss2.addViewer(values2);
}
// Add new commenter
if (accessLevel == 'Comment') {
var addCommenters = ss2.addCommenter(values2);
}
}
}
The Spreadsheet object does not support the addCommentor() method. You should use DriveApp service instead.
DriveApp.getFileById(id).addCommenter(emailAddress)
How to search a column on a sheet for a value, and if the value is there continue code? I am trying to make an update system to check to see if their email is on a sheet. If their email is on a sheet then it will check if their system version is up to date. If the system is not to up to date it will then copy their data, delete their current sheet, create a copy from an example then put in their data. If the user does not have the system it will create one for them. It seems to continuously skip Checking their email.
My code uses URLs and IDs but I have taken them out for obvious reasons. Below is an example of the beginning of my code.
function readlog()
var user = Session.getEffectiveUser().getUsername();
var email = Session.getEffectiveUser().getEmail();
var ss = SpreadsheetApp.openByUrl(URL_);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var sheet = sheet.getSheetByName('8th grade')
var active = sheet.getRange('8th grade!b3:b').getValues()
if (email == active) {
//do something
}
Here is a full version of my code:
function readlog(){
var user = Session.getEffectiveUser().getUsername();
var email = Session.getEffectiveUser().getEmail();
var timezone= "CST";
var date = Utilities.formatDate(new Date(),timezone, "E MMM dd,yyyy HH:mm:ss");
var ss = SpreadsheetApp.openByUrl(URL_);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var sheet = sheet.getSheetByName('8th grade')
var active = sheet.getRange('8th grade!b3:b').getValues()
if (email == active) {
var container = DriveApp.getFoldersByName('Reading Log')
var fid = DriveApp.getFoldersByName('Reading Log').getId()
var version = sheet.getRange('8th grade!a1')
var update = container.getDescription();
if (update == version) {
var ui = SpreadsheetApp.getUi();
var response = ui.alert('You already have a reading log, and you have the most recent update!', ui.ButtonSet.OK);
} else {
var contents = container.getFiles();
var files = DriveApp.getFolderById(fid).searchFiles(
'title contains "Reading log"');
while (files.hasNext()) {
var file = files.next();
var logtoupdate = file.getUrl;
}
var ss = SpreadsheetApp.openByUrl(logtoupdate);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var logrange = sheet.getRange('8th Grade!e5:o').getValues()
SpreadsheetApp.getActiveSpreadsheet().deleteActiveSheet();
var master = DriveApp.getFileById(URL_);
var read = master.makeCopy("Reading Log",container);
var target = read.getRange('8th Grade e5:o').setValues(logrange);
var range = sheet.getRange("A1:B2");
range.setValues([[50, 100]]);
var ss = SpreadsheetApp.openByUrl(URL_);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet()
}
} else {
var ss = SpreadsheetApp.openByUrl(URL_);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var targetFolder = DriveApp.createFolder("Reading Log");
var eighth = DriveApp.getFileById(URL_);
var share = eighth.makeCopy("(Name): 8th Grade Reading Log",targetFolder);
var master = DriveApp.getFileById(URL_);
var read = master.makeCopy("Reading Log",targetFolder);
var folder = sheet.getRange('8th grade!a1');
targetFolder.setDescription(folder);
var idsheet = read.getUrl();
var idshare = share.getUrl();
var idfolder = targetFolder.getUrl()
sheet.appendRow([user,email,date,idfolder,idsheet,idshare]);
var ui = SpreadsheetApp.getUi();
var response = ui.alert('Your Reading log is created. There is now a folder in your google drive called Reading log. Have Fun Reading!', ui.ButtonSet.OK);
}
}
Short answer
Instead of email == active use active.join('|').split('|').indexOf(email)
Explanation
getValues() return a two dimensional array.
join('|') convert this array into an string using | as separator.
split('|') convert the above string into an (one dimension) array.
indexOf(email) returns the index of the email value on the above array. If the email value is not found, -1 is returned.
On a comparison -1 is parsed as false.
This question already has an answer here:
How to fix 'TypeError: Cannot call method "getRange" of null' in Google Apps Script
(1 answer)
Closed 5 months ago.
I'm trying to publish this code, but everytime when I run this code I get an error
Cannot call method"getDataRange" of null.
Here is my code
function
doGet() {
var ss = SpreadsheetApp.openById('sheet id');
var sheet = ss.getSheetByName('sheet name');
var data = sheet.getDataRange();
var dateFilter= Charts.newCategoryFilter().setFilterColumnIndex(0).build();
var ageFilter = Charts.newNumberRangeFilter().setFilterColumnIndex(7).build();
var transportFilter = Charts.newCategoryFilter().setFilterColumnIndex(2).build();
var nameFilter = Charts.newStringFilter().setFilterColumnIndex(1).build();
var tableChart = Charts.newTableChart().setDimensions(700, 300)
.setDataViewDefinition(Charts.newDataViewDefinition().setColumns([0,1,2,3,4,5,6,7]))
.build();
var pieChart = Charts.newPieChart()
.setDataViewDefinition(Charts.newDataViewDefinition()
.setColumns([1,7])).build();
var dashboard = Charts.newDashboardPanel().setDataTable(data)
.bind([dateFilter,ageFilter, transportFilter, nameFilter], [tableChart, pieChart])
.build();
var app = UiApp.createApplication().setHeight(50);
var todaysdate = new Date();
app.add(app.createLabel(todaysdate));
app.add(app.createHTML('<h1 style="text-align:center;">DEMO</h1>'));
var filterPanel = app.createHorizontalPanel();
var chartPanel = app.createHorizontalPanel();
filterPanel.add(dateFilter).add(ageFilter).add(transportFilter).add(nameFilter).setSpacing(10);
chartPanel.add(tableChart).add(pieChart).setSpacing(50);
dashboard.add(app.createVerticalPanel().add(filterPanel).add(chartPanel));
app.add(dashboard);
var service = ScriptApp.getService();
service.enable(service.Restriction.ALL);
return app;
}
The error indicate sheet is null. Make sure you are using the correct sheet name in var sheet = ss.getSheetByName('sheet name');. Copy and paste the sheet name from the google doc if there are invisible characters.