Form data submit to external sheet (google script) - javascript

I have created a data entry form in google sheets, now I am having trouble saving said entry to an external sheet so far this is what I have, I do not know if I am using the right method to reference sheet.
please look at comments, thank you
Everytime I am trying to submit the form it is giving lastRow Null
function submitData() {
//variable declaration for referenceing the active google sheet
var myGoogleSheet = SpreadsheetApp.getActiveSpreadsheet();
var shUserForm = myGoogleSheet.getSheetByName('MasterSheet');
//open external sheet
var extSS = SpreadsheetApp.openById("1U9SmfPCH9v8maqh6XL0dmRL85TJZfckUV7SAEGM3pQo");
var datasheet= extSS.getSheetByName("Mastersheet");
var srcData = shUserForm.getDataRange().getValues();
//to create the instance of the ui environment to use the alert features
var ui = SpreadsheetApp.getUi();
var response = ui.alert("Submit", "Do you want to submit the data?", ui.ButtonSet.YES_NO);
//checking the user response
if ( response == ui.NO) {
return; // to ext from this function
}
if ( validateEntry()== true) {
var blankRow =datasheet.getLastRow() + 1; //identify the next blank row
//'code to update the database sheet ( write data entry to DB sheet)
datasheet.getRange(blankRow,1).setValue(srcData.getRange("C7").getValue()); //input number
datasheet.getRange(blankRow,2).setValue(srcData.getRange("C9").getValue()); //Department
datasheet.getRange(blankRow,3).setValue(srcData.getRange("C11").getValue()); //Agent Name
datasheet.getRange(blankRow,4).setValue(srcData.getRange("C13").getValue()); //Hub location
datasheet.getRange(blankRow,9).setValue(srcData.getRange("C15").getValue()); //order ID
datasheet.getRange(blankRow,10).setValue(srcData.getRange("C20").getValue()); //type of entry
datasheet.getRange(blankRow,5).setValue(Session.getActiveUser().getEmail()); //Submitted By, this will automatically get user email
datasheet.getRange(blankRow,7).setValue(new Date()).setNumberFormat('yyyy-mm-dd h:mm:');
datasheet.getRange(blankRow,8).setValue(new Date()).setNumberFormat('yyyy-mm-dd h:mm:');
datasheet.getRange(blankRow,6).setValue(srcData.getRange("C17").getValue()); //comments
ui.alert(' "New Data Saved - Input #' + shUserForm.getRange("C7").getValue() + '"');
shUserForm.getRange("C7").clear();
shUserForm.getRange("C9").clear();
shUserForm.getRange("C11").clear();
shUserForm.getRange("C13").clear();
shUserForm.getRange("C15").clear();
shUserForm.getRange("C17").clear();
}
}

To save data to another Spreadsheet, You need to open it first by using either openById("insert sheet id here") or openByUrl("insert sheet URL here"). This will return a Spreadsheet class which has getSheetByName("sheet name") method you can use to access the Sheet.
ID of the spreadsheet can be found in the url. This can be found after /d/ or before /edit
Example ID:
https://docs.google.com/spreadsheets/d/12345/edit#gid=0
12345 is the Spreadsheet ID
Example:
Code:
function saveData() {
//open current sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("Sheet1");
//open external sheet
var extSS = SpreadsheetApp.openById("Insert External Spreadsheet ID here");
var extSH = extSS.getSheetByName("Sheet1 External");
//get data from current Sheet.
var srcData = sh.getDataRange().getValues();
//write to external sheet
extSH.getRange(extSH.getLastRow()+1, 1, srcData.length, srcData[0].length).setValues(srcData);
}
This script will paste the values from Sheet1 to Sheet2
Before:
Sheet1 Data:
Sheet2 Data:
After:
Sheet1 Data:
Sheet2 Data:
SpreadsheetApp.openByID()
SpreadsheetApp.openByURL()
Spreadsheet.getSheetByName()
Class Sheet
Class Range

Related

How do i copy the whole row if the value in a particular column is as required?

I need some help here...
What I want to do is copy all the rows from a sheet which have a value 'open POs' in column R in other words every row that has a value 'open POs' in column R should be copied to another google sheet.
Please help...
Try this:
Code:
function myFunction() {
// Source sheet is the current sheet
var srcSheet = SpreadsheetApp.getActiveSheet();
// Open destination sheet using spreadsheet ID found in url
// See reference below on how top locate spreadsheet id
var dstSheet = SpreadsheetApp.openById('destination sheet ID');
// Get values of source sheet
var srcData = srcSheet.getDataRange().getValues();
srcData.forEach(function(row){
// If column R is 'open POs'
if(row[17] == 'open POs') {
// Add to last row of dstSheet
dstSheet.appendRow(row)
}
});
// Send destination sheet link to email with subject
MailApp.sendEmail("email#gmail.com", "subject", dstSheet.getUrl());
}
Data Sample:
Output:
Note:
Columns hidden for column R visibility
Reference:
Spreadsheet ID

How to create macro to hide/show sheets automatically depending of a condition?

I'm totally lost here!
My spreadsheet has one sheet " Product Master Record" with a table containing three columns: Product ID (numerical) | Product Description | Product Status.
Each product has its own sheet within the spreadsheet.
The name of each sheet depends on the product status:
- "Active" product: sheet name = product name --> Sheet is visible
- "Inactive" product: sheet name = product ID --> Sheet is hidden
So I'm trying to write a macro which hide/shows sheets depending on the condition:
Product status (active/inactive)
Sheet name (if name contains text or not)
I don't need to write both conditions; only the easiest one to code.
Any ideas??
Thank you!
Here the sample for your purpose, ProdMaster, row 1 header [ProdId,Desc,Status], and rows afterward are data, and Status will be Inactive and Active:
function HideSheets() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName('ProdMaster');
var lrow = sheet.getLastRow();
var myValue = sheet.getRange("A2:C" + lrow).getValues();
for (a=1; a<myValue.length+1; a++)
{
var target = myValue[a-1];
var tsheet = spreadsheet.getSheetByName(target[0]);
if(tsheet==null) spreadsheet.insertSheet(target[0]);
if(target[2]=='Active') tsheet.showSheet();
if(target[2]=='Inactive') tsheet.hideSheet();
}
};
As a way for solving your problem you could do the following, instead of using "Active" or "Inactive" as checkers for validating a boolean condition, in your "Product Master Record" you could set the status using the functions TRUE and FALSE, in that way you could decouple hardcoded text from your code and avoid the trouble from someone misspelling the words "Active" or "Inactive".
function HideSheets() {
// Get the active sheet and range of rows you want
var spreadSheet = SpreadsheetApp.getActive();
var mainSheet = spreadSheet.getSheetByName('Product Master Record');
var rows = mainSheet.getRange("A2:C" + mainSheet.getLastRow()).getValues();
// Iterate over all rows
for(row in rows){
// Get the sheets from their names and check if not null
var secondarySheet = spreadSheet.getSheetByName(rows[row][0]);
if(secondarySheet){
if(rows[row][2]) secondarySheet.showSheet(); // show the sheet if value is true
if(!rows[row][2]) secondarySheet.hideSheet(); // hide sheet if value is false
}
}
};
Docs
I can see your new in this wonderful world. I will give you some docs to help you in your path of learning:
Google Apps Script Reference
Overview of Google Apps Script
Class Sheet
Thank you all!
Finally I found help with a colleague and it works. This is the code in case someone finds useful:
function updateSheetFromIndex(index)
{
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();
var activeSheet = ss.getSheetByName(sheetNameOfTheMenu);
var cell = activeSheet.getRange(index, 5);
var formula = cell.getFormula();
var regExpr = /\#gid=([0-9]*)"/;
var result = regExpr.exec(formula);
var cellStatus = activeSheet.getRange(index, 4);
Logger.log(index)
if (result != null) {
var gid = result[1];
for each (var sheet in SpreadsheetApp.getActive().getSheets()) {
if(sheet.getSheetId()==gid){
if (cellStatus.getValue() == "Activo") {
Logger.log("Activo---");
sheet.showSheet();
}
if (cellStatus.getValue() == "Inactivo") {
Logger.log("Inactivo---");
sheet.hideSheet();
}
break;
}
}
} else {
Logger.log("+++ No pattern matches");
Logger.log("Formula");
Logger.log(formula);
}
}

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();
}

Google Sheets App Script Find and Replace

I'm trying to do something but I'm not too code savy.
I have two sheets, one has a two columns "Status" and "ID", then I have a second sheet that is blank. The first sheet is huge but I need a script in which I can paste a bunch of random IDs into the blank sheet then run this script and it will search the ID column of sheet 1, if any ID on Sheet 2 matches the ID on sheet 1 then change the status from "On Hold" to "Sent"
I think I'm headed in the right direction but I'm not having much luck.
Here's what I have:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Script Menu')
.addItem('Run Script', 'Sent')
.addToUi();
}
function SentToOCS() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getSheetByName("Sent IDs"); //Sheet containing IDs
var sheet1 = ss.getSheetByName("sheet1");
var searchData = source.getDataRange().getValues(); //The IDs we want to find
var ids = sheet1.getDataRange().getValues(); //Data Range and values of data to search
var status = sheet1.getDataRange(); //Data Range of "On Hold" status
for (var j = 0; j<searchData.length; j++){
for (var i = 0; i<ids.length; i++) {
if (ids(i) == searchData(j)){
status(i) == "Sent";
}
}
}
}

Send Only Active Sheet as PDF Attachment through GMail in Google Sheet

Right now, my code is sending my entire Google Sheet file as a PDF attachment. I am needing it, though, to only send my one tab entitled "PO Template". Let me know if you can help:
function emailGoogleSpreadsheetAsPDF() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var email = ss.getRange("A19").getValue();
var PO = ss.getRange("N3").getValue();
var subject = "PO No. " + PO;
var blob =
DriveApp.getFileById(shs.getId()).getAs("Application/pdf");
var body = "Install the <a href='http://www.labnol.org/email-
sheet'>Email Spreadsheet add-on</a> for one-click conversion.";
blob.setName(ss.getName()+".pdf");
if(MailApp.getRemainingDailyQuota()>0)
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments:[blob]
});
}
Don't think there's an adhoc method to do this. You'll have to resort to a workaround as suggested by this github tutorial:
// Create a new Spreadsheet and copy the current sheet into it.
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var projectname = SpreadsheetApp.getActiveSpreadsheet();
sheet = originalSpreadsheet.getActiveSheet();
sheet.copyTo(newSpreadsheet);
// Find and delete the default "Sheet 1", after the copy to avoid triggering an apocalypse
newSpreadsheet.getSheetByName('Sheet1').activate();
newSpreadsheet.deleteActiveSheet();

Categories