how to increment a global variable in JavaScript every time a function runs in Google Apps Script? [duplicate] - javascript

This question already has answers here:
How to define global variable in Google Apps Script
(8 answers)
Global variables in Google Script (spreadsheet)
(3 answers)
Closed 4 months ago.
This adapted code:
var count = 0;
function AddRecord(name) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("data");
var cell = sheet.getRange("F5");
cell.setValue(name);
cell = sheet.getRange("B2");
cell.setValue(count);
count = count + 1;
}
function startForm() {
var form = HtmlService.createHtmlOutputFromFile('AddForm');
SpreadsheetApp.getUi().showModalDialog(form, 'Add Record');
}
function addMenu() {
var menu = SpreadsheetApp.getUi().createMenu('Custom');
menu.addItem('Add Record Form', 'startForm');
menu.addToUi();
}
function onOpen(e) {
addMenu();
}
works as expected, in that it writes the expected values, name and count, to their respective cells. However, the value for count remains unchanged. How is the count variable incremented every time the AddRecord function executes?
This const counter = ((count = 0) => () => count++)(); would seem to be at least the shortest solution suggested.

Modification points:
When a function AddRecord(name) of Google Apps Script is run from google.script.run.AddRecord(name) of Javascript, unfortunately, var count = 0; is always run. By this, count is not changed from 0 every run of the function, and the value of count is not kept. I thought that this is the reason for your issue.
If you want to keep the count and when AddRecord(name) is run, you want to count up the value of count, how about the following modification? In this modification, I used PropertiesService.
Modified script:
In this modification, the value of count is kept even when the dialog is closed.
function AddRecord(name) {
var p = PropertiesService.getScriptProperties();
var count = p.getProperty("count")
count = count ? Number(count) : 0;
// This is your current script.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("data");
var cell = sheet.getRange("F5");
cell.setValue(name);
cell = sheet.getRange("B2");
cell.setValue(count);
count = count + 1;
// Browser.msgBox(count); // If you use this, when "AddRecord" is run, you can see the current value of "count" in a dialog.
p.setProperty("count", count);
}
// When you want to reset the value of "count", please run this function.
function resetCounter() {
PropertiesService.getScriptProperties().deleteProperty("count");
}
function startForm() {
var form = HtmlService.createHtmlOutputFromFile('AddForm');
SpreadsheetApp.getUi().showModalDialog(form, 'Add Record');
}
In this modification, when AddRecord is run from Javascript, "count" is retrieved from PropertiesService and the value is increased and the updated value is stored in PropertiesService. By this, the value of "count" is kept.
Note:
At the above-modified script, only Google Apps Script is used. As another direction, if you can also use the HTML side, how about the following modification? In this modification, the value of count is cleared when the dialog is closed.
Google Apps Script side:
function AddRecord(name, count) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("data");
var cell = sheet.getRange("F5");
cell.setValue(name);
cell = sheet.getRange("B2");
cell.setValue(count);
count = count + 1;
return count;
}
function startForm() {
var form = HtmlService.createHtmlOutputFromFile('AddForm');
SpreadsheetApp.getUi().showModalDialog(form, 'Add Record');
}
HTML side: This HTML is from your showing URL.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
let count = 0;
function AddRow()
{
var name = document.getElementById("name").value;
google.script.run.withSuccessHandler(e => {
count = e;
console.log(count);
}).AddRecord(name, count);
}
</script>
</head>
<body>
Name: <input type="text" id="name" />
<input type="button" value="Add" onclick="AddRow()" />
</body>
</html>
When this script is run, when the button is clicked, count is increased. You can see it in the console of the browser.
Reference:
Properties Service

Related

Add/Update Google Sheet Row Data Comparing Values from HTML Form Using Google Apps Script - Trying to Find Match on Sheet & Update Selected Row Data

I have an HTML form that allows users to populate the form from a Google Sheet, and successfully add new rows to the Sheet. I created the Apps Script according to this tutorial.
I am trying to expand the function of my Apps Script to search the rows of entries for duplicates based on data from two columns and if there is a match, overwrite the existing row.
I know I need a for loop that iterates through each row in the Google Sheet to compare to the form data fields in question, but I don't know how to access each.
This is a shortened example of the the form (the actual is much longer):
<form id="form">
<form id="form">
<input name="firstName" placeholder="firstName" />
<input name="lastName" placeholder="lastName" />
<input name="someOtherField" placeholder="someOtherField" />
<input name="someFourthField" placeholder="someOtherField" />
<div class="btn-success btn" onclick="SaveData()">Save Data</div>
</form>
</form>
<script>
function SaveData() {
var formData = new FormData(document.getElementById("form"));
fetch('https://script.google.com/macros/s/AKfycbwQFSXfeOKBHzf41MF6Nh5XIOjaPvr159-blUxsg5smD3BDH8qB4RUZRRo8q9nCJLb18w/exec',
{
method: 'post',
body: formData,
})
}
</script>
My Apps Script works perfectly when adding new rows, but either my for loop is not written correctly and thus not finding matches or otherwise setting the nextRow index isn't working:
var sheetName = 'Entries'
var scriptProp = PropertiesService.getScriptProperties()
function intialSetup () {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
scriptProp.setProperty('key', activeSpreadsheet.getId())
}
function doPost (e) {
var lock = LockService.getScriptLock()
lock.tryLock(10000)
try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
var nextRow = sheet.getLastRow() + 1
var newRow = headers.map(function(header) {
return header === 'timestamp' ? new Date() : e.parameter[header]
})
var range = sheet.getDataRange();
var rangeData = range.getValues();
// Here is where the script is failing to find a match in the spreadsheet
for(i = 1; i > rangeData.length; i++) {
if(rangeData[i][0] == e.firstName && rangeData[i][1] == e.lastName)
{
nextRow = i;
}
}
sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
.setMimeType(ContentService.MimeType.JSON)
}
catch (e) {
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
.setMimeType(ContentService.MimeType.JSON)
}
finally {
lock.releaseLock()
}
}
With the above script, every form entry creates a new row, the match is never true. So I think there is something wrong either with my logic in matchfinding or the syntax I'm using to find the form values and spreadsheet data. So what am I missing?
Thanks!
EDIT:
To help elaborate this example, I have attached a screenshot of a sample spreadsheet. As is, if a user submits a form with firstName "Bob" and lastName "Belcher," I would like to have the remaining form data overwrite the existing row with those names. But if the firstName and lastName fields have no match in the spreadsheet, add a new row.
The above script always adds new rows even if there is an existing row. I tried using the logic from this question to achieve my desired result but this caused the script to fail entirely (no updated rows and no added rows). I also tried using the logic steps outlined in this video which uses "indexOf" form data instead of a for loop with if statement to find matches. This solution also did not work
Spreadsheet Screenshot
EDIT EDIT:
I have made the whole script available and recorded a short video of the current script behavior versus the desired behavior. Hopefully this clarifies my question. Thanks!
I believe your goal is as follows.
When the HTML form is submitted, you want to check the values of firstName and lastName from the Spreadsheet. And, when those values are existing in the Spreadsheet, you want to update the row. When those values are not existing in the Spreadsheet, you want to append the data as a new row.
When your script is modified for achieving this, how about the following modification?
From:
for(i = 1; i > rangeData.length; i++) {
if(rangeData[i][0] == e.firstName && rangeData[i][1] == e.lastName)
{
nextRow = i;
}
}
To:
for (var i = 0; i < rangeData.length; i++) {
if (rangeData[i][0] == e.parameter.firstName && rangeData[i][1] == e.parameter.lastName) {
nextRow = i + 1;
break;
}
}
In your showing script, in the case of for(i = 1; i > rangeData.length; i++), no loop is done. And, e.firstName and e.lastName are always undefined. And also, in your script, it is required to finish the loop when the values were found.
Note:
When you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.
You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".

Google Sheet / Apps script / Trigger when a new row is added [duplicate]

This question already has answers here:
Running onEdit trigger when sheet is updated by Zapier
(2 answers)
Closed 1 year ago.
I am currently working on an Apps Script on a google sheet file. I made a script that sends mail to contacts. In my sheet the contacts are in the form of a line which is automatically added with a zapier. I have installed an onChange trigger but I would like it to act only when a new row is added to my sheet, I have looked everywhere but no solutions work or correspond to my problem. So if anybody have an idea to solve it, it would be helpfull
(I put you a copy of my script below)
thanks in advance
'
function envoie_mail (){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1=ss.getSheetByName('testmail');
var lr = sheet1.getLastRow();
var eligible = sheet1.getRange(lr,4).getValue();
var emailadresse = sheet1.getRange(lr,1).getValue();
var subject = sheet1.getRange(lr,2).getValue();
if (eligible === "non"){
var htmlTemplate = HtmlService.createTemplateFromFile("body.html");
var modele = htmlTemplate.evaluate().getContent();
var reference = sheet1.getRange(lr,3).getValue();
modele = modele.replace("<ref>",reference).replace("<ref2>",reference);
MailApp.sendEmail({
to: emailadresse,
subject: subject,
htmlBody: modele
});
}
}
I don't know how zapier works, howerver try to put an indicator and test as follows
function createSpreadsheetChangeTrigger() {
var ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger('onChange')
.forSpreadsheet(ss)
.onChange()
.create();
}
function onChange(e) {
var f = SpreadsheetApp.getActiveSheet()
var data = f.getRange(1,f.getLastColumn(),f.getLastRow(),1).getValues().join().split(',')
for (var i=0;i<data.length;i++){
if (data[i]=='') {
Browser.msgBox('envoi mail ligne ' + (i+1))
f.getRange((i+1),f.getLastColumn()).setValue('ok')
}
}
}
https://docs.google.com/spreadsheets/d/1TEWS1e3uOnYybgbuScWb9plA9J7rgVjt16g9Ucg0x3M/copy

How do I add a new value to a Google Sheet from a text field in a Web App and then automatically update the associated dropdown?

WARNING: I'm not a programmer by trade.
Ok. Got the disclaimer out of the way. So this might not be the best way to do this but here is the scenario. I have a dropdown that gets populated via a Google Sheet. The user chooses a selection from the list but this dropdown does not have all of the possible values it could have. There will likely be a time when the user needs a new value added. While I could manually update the spreadsheet as new values are requested that introduces an element of human availability to get this done and I'm not always available.
What I would prefer is a self-serve model. I want to supply the user with a text field where they can enter the new value and submit it to the Google Sheet. Then I would like the dropdown to be updated with the new value for the user to choose.
Now, I realize that I could just submit the value in the new field to the Google Sheet but that will require building a condition to see whether it is the dropdown or text field that has a value in it. I'd also need some type of error handling in case both the dropdown and text field have values. That seems like a bigger headache to program then my ask.
I'm not sure what code you would need to see to help make this work but here is what I think might help.
doGet function
function doGet(e){
var ss = SpreadsheetApp.openById(ssId)
var ws = ss.getSheetByName("External");
var range = ws.getRange("A2:D2");
var valuesArray = [];
for (var i = 1; i <= range.getLastColumn(); i++){
var lastRowInColumn = range.getCell(1, i).getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
var list = ws.getRange(2,i,lastRowInColumn-1,1).getValues();
valuesArray.push(list);
}
var userEmail = Session.getActiveUser().getEmail();
var sourceListArray = valuesArray[2].map(function(r){ return '<option>' + r[0] + '</option>'; }).join('');
var productListArray = valuesArray[3].map(function(r){ return '<option>' + r[0] + '</option>'; }).join('');
var tmp = HtmlService.createTemplateFromFile("config");
tmp.productList = productListArray;
return tmp.evaluate();
}
Add to Google Sheet
function userClicked(tagInfo){
var ss = SpreadsheetApp.openById(ssId)
var ws = ss.getSheetByName("Data");
ws.appendRow([tagInfo.email, tagInfo.source, tagInfo.product, new Date()]);
}
Add record
function addRecord(){
var tagInfo = {};
tagInfo.product = document.getElementById("product").value;
google.script.run.userClicked(tagInfo);
var myApp = document.getElementById("source");
myApp.selectedIndex = 0;
M.FormSelect.init(myApp);
var myApp = document.getElementById("brand");
myApp.selectedIndex = 0;
M.FormSelect.init(myApp);
var myApp = document.getElementById("product");
myApp.selectedIndex = 0;
M.FormSelect.init(myApp);
}
How dropdowns are populated in the HTML.
<div class="input-field col s3">
<select id="product" onchange="buildURL()">
<option disabled selected value="">Choose a product</option>
<?!= productList; ?>
</select>
<label>Product</label>
</div>
Need to see anything else? I think it might be relatively easy to add the new value to the column but the tricky part seems to be the update of only that one dropdown and not the entire app. To me it seems like I want to trigger the doGet() function again but only for that specific dropdown. Thoughts?
UPDATE: current code to add new value to dropdown
function addProduct() {
let newProd = document.getElementById("newProduct").value;
google.script.run.withSuccessHandler(updateProductDropdown).addNewProduct(newProd);
document.getElementById("newProduct").value = "";
}
function updateProductDropdown(newProd){
var newOption = document.createElement('option');
newOption.value = newProd;
newOption.text = newProd;
document.getElementById('product').add(newOption);
}
UPDATE2: App Scripts function to add new value to column in spreadsheet
function addNewProduct(newProd){
var columnLetterToGet, columnNumberToGet, direction, lastRow, lastRowInThisColWithData, rng, rowToSet, startOfSearch, valuesToSet;
var ss = SpreadsheetApp.openById(ssId);
var ws = ss.getSheetByName("List Source - External");
lastRow = ws.getLastRow();
//Logger.log('lastRow: ' + lastRow)
columnNumberToGet = 9;//Edit this and enter the column number
columnLetterToGet = "I";//Edit this and enter the column letter to get
startOfSearch = columnLetterToGet + (lastRow).toString();//Edit and replace with column letter to get
//Logger.log('startOfSearch: ' + startOfSearch)
rng = ws.getRange(startOfSearch);
direction = rng.getNextDataCell(SpreadsheetApp.Direction.UP);//This starts
//the search at the bottom of the sheet and goes up until it finds the
//first cell with a value in it
//Logger.log('Last Cell: ' + direction.getA1Notation())
lastRowInThisColWithData = direction.getRow();
//Logger.log('lastRowInThisColWithData: ' + lastRowInThisColWithData)
rowToSet = lastRowInThisColWithData + 1;
valuesToSet = [newProd];
ws.getRange(rowToSet, 9).setValues([valuesToSet]);
return newProd;
}
SOLUTION to Update Materialize Dropdown
function updateProductDropdown(newProd){
newProdOption = document.getElementById('product');
newProdOption.innerHTML += '<option>' + newProd + '</option>';
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
}
You can specify a client side callback function if you use google.script.run withSuccessHandler(callback) where your callback could update the list only and not the whole site.
Example:
google.script.run.withSuccessHandler(updateDropdownWidget).updateDropdownList(text_from_input)
Where updateDrownList(text_from_input) is a function in your Apps Script that adds text to the sheet using SpreadsheetApp for example, and returns the "text" to the callback function: updateDropdownWidget(text) which adds a new list item to the HTML drop-down list in your front end.
index.html:
<form>
<label for="newOption">New option for the dropdown:</label>
<input type="text" id="nopt" name="newOption">
<input type="button" value="Submit"
onclick="google.script.run.withSuccessHandler(updateDropdownWidget)
.updateDropdownList(document.getElementById('nopt').value)">
</form>
<label for="cars">Choose a car:</label>
<select name="cars" id="cars">
<?!= values; ?>
</select>
<script>
function updateDropdownWidget(text){
var option = document.createElement('option');
option.value = text;
option.text = text;
document.getElementById('cars').add(option);
}
</script>
Code.gs:
function doGet(e){
var ss = SpreadsheetApp.getActiveSheet();
var lastRow = ss.getDataRange().getLastRow();
var values = ss.getRange(1,1,lastRow,1).getValues();
var valuesArray = [];
for (var i = 0; i < values.length; i++){
valuesArray.push('<option value="'+values[i]+'">' +values[i]+ '</option>');
}
var tmp = HtmlService.createTemplateFromFile("index");
tmp.values = valuesArray;
return tmp.evaluate();
}
function updateDropdownList(text_from_input){
// Log the user input to the console
console.log(text_from_input);
// Write it to the sheet below the rest of the options
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getDataRange().getLastRow();
sheet.getRange(lastRow+1,1).setValue(text_from_input);
// Return the value to the callback
return text_from_input;
}
Here's an example:
In my Stack Over Flow spreadsheet I four buttons which can be used to run any function in 3 script files and every time I load the sidebar it reads the functions in those script files and returns them to each of the select boxes next to each button so that I test functions that I write for SO with a single click and I can select any function for any button. Here's the Javascript:
$(function(){//JQuery readystate function
google.script.run
.withSuccessHandler(function(vA){
let idA=["func1","func2","func3","func4"];
idA.forEach(function(id){
updateSelect(vA,id);
});
})
.getProjectFunctionNames();
})
Here is GS:
function getProjectFunctionNames() {
const vfilesA=["ag1","ag2","ag3"];
const scriptId="script id";
const url = "https://script.googleapis.com/v1/projects/" + scriptId + "/content?fields=files(functionSet%2Cname)";
const options = {"method":"get","headers": {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}};
const res = UrlFetchApp.fetch(url, options);
let html=res.getContentText();
//SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), "Project Functions");
let data=JSON.parse(res.getContentText());
let funcList=[];
let files=data.files;
files.forEach(function(Obj){
if(vfilesA.indexOf(Obj.name)!=-1) {
if(Obj.functionSet.values) {
Obj.functionSet.values.forEach(function(fObj){
funcList.push(fObj.name);
});
}
}
});
//SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(funcList.join(', ')), "Project Functions");
return funcList;//returns to withSuccessHandler
}
Image:
Animation:

Convert VBA to Java Google Script [duplicate]

This question already has answers here:
How to convert VBA script to Google Apps Script automatically?
(3 answers)
Closed 1 year ago.
Have the below VBA and i need to insert it into a Google Sheet,
Can somebody help with the conversion?
Sub Activate_Sheet()
Sheets(Sheets("Main").Range("A1").Value).Activate
End Sub
Thanks,
This script gets the value in cell A1 in sheet()[0], and then moves to that sheet number.
function so_53361440() {
// set up spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
// set sheet 0 as the active sheet
var sheet = ss.getSheets()[0];
// get the value in cell A1
var cell = sheet.getRange("A1").getValue();
// Logger.log("value of cell = "+cell);// DEBUG
// Convert number to string
var sheetname = ""+ cell;
// Logger.log("sheetname = "+sheetname);// DEBUG
// set sheet by name and move to new sheet
var mysheet = ss.getSheetByName(sheetname);
ss.setActiveSheet(mysheet);
}
Variation on a theme
With 300 sheets, going back to sheet()[0] will get frustrating. So this small variation is designed to create a custom menu that will request the sheet number in an inputbox. The rest of the code is the same
function so_53361440_01() {
// setup ui
var ui = SpreadsheetApp.getUi();
var result = ui.prompt(
'What sheet do you want?',
'Please enter a number:',
ui.ButtonSet.OK_CANCEL);
// Process the user's response.
var button = result.getSelectedButton();
var text = result.getResponseText();
if (button == ui.Button.OK) {
// User clicked "OK".
//ui.alert('Sheet is ' + text + '.');
} else if (button == ui.Button.CANCEL) {
// User clicked "Cancel".
ui.alert('Operation Cancelled.');
} else if (button == ui.Button.CLOSE) {
// User clicked X in the title bar.
ui.alert('Input Box closed - no action taken.');
}
// set up spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
// assign the UI value to a variable
var cell = text;
// Logger.log("value of cell = "+cell);//DEBUG
// convert the variable to a string
var sheetname = ""+ cell;
// Logger.log("sheetname = "+sheetname);// DEBUG
// set the sheetname to the variable and goto that sheet
var mysheet = ss.getSheetByName(sheetname);
ss.setActiveSheet(mysheet);
}
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Change Sheet')
.addItem('Pick a sheet', 'so_53361440_01')
.addToUi();
}

Define variable based on form input in Google Apps Script (Spreadsheet)

I want to have a form that allows the user to input some data, that then gets stored in variables for use in other functions. Specifically, I just need them to be able to define the name of two sheets (shtName and databaseName).
I can't get the variable to work in the script though as it tells me the variables are undefined (referring to shtName & databaseName here).
I get this error: ReferenceError: "shtName" is not defined.
If I define shtName and databaseName outside a function, it works. So that's obviously the problem but not sure how to get around it.
index.html
<html>
<head>
<base target="_top">
</head>
<body>
<form name="myForm">
Name of current sheet:<br>
<input type="text" name="formshtname" >
<br><br>
Which database sheet to search in?<br>
<input type="text" name="formtagdatabase">
<br><br>
<input type="button" value="Submit"
onclick="google.script.run
.withSuccessHandler(google.script.host.close)
.formSubmit(this.parentNode)" />
<input type="button" value="Close" onclick="google.script.host.close()" />
</form>
</body>
</html>
addTags.gs
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Tags')
.addItem('Setup', 'openSetup')
.addSeparator()
.addItem('Add tags', 'findingTags3')
.addToUi();
}
function openSetup() {
var html = HtmlService.createHtmlOutputFromFile('index').setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'To auto complete tags, fill in the form');
}
function formSubmit(form) {
var shtName = form.formshtname;
var databaseName = form.formtagdatabase;
}
function findingTags3() {
// bunch of code
/* current spreadsheet */
var spreadsheet = SpreadsheetApp.getActive()
var sht = SpreadsheetApp.setActiveSheet(spreadsheet.getSheetByName(shtName)); // want this to be defined from form
/* tag database spreadsheet */
var spreadsheet2 = SpreadsheetApp.openById("xxx");
var sht2 = spreadsheet2.getSheetByName(databaseName); // want this to be defined from form
// more code
}
EDIT:
Ok, one way of doing it is by adding this inside function findingtags3()
var shtName = Browser.inputBox("Current sheet name");
var databaseName = Browser.inputBox("Input sheet name of database you want to search");
I suppose that will do, but it would be nicer to have a proper setup where you enter that information and it gets stored, until you change the input.
You can use propertiesService to store you variable until you are ready to execute the function.
Your code will look like this:
function exampleSubmit(){ // this function will set a mock/default values to properties
var form = {
"formshtname" : "Sheet1",
"formtagdatabase" : "Sheet4"
}
Logger.log(form)
formSubmit(form)
}
function formSubmit(form) {
var docProp = PropertiesService.getDocumentProperties()
docProp.setProperty("shtname", form.formshtname)
docProp.setProperty("databaseName",form.formtagdatabase)
}
function findingTags3() {
// bunch of code
var docProp = PropertiesService.getDocumentProperties()
var shtName = docProp.getProperty("shtname")
var databaseName = docProp.getProperty("databaseName")
/* current spreadsheet */
var spreadsheet = SpreadsheetApp.getActive()
var sht = SpreadsheetApp.setActiveSheet(spreadsheet.getSheetByName(shtName)); // want this to be defined from form
Logger.log(sht.getName())
/* tag database spreadsheet */
var spreadsheet2 = SpreadsheetApp.openById("xxx");
var sht2 = spreadsheet2.getSheetByName(databaseName); // want this to be defined from form
Logger.log(sht2.getName())
// more code
}
This is document specific property if you want this values to be unique for each user. Use user properties instead.

Categories