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";
}
}
}
}
Related
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
I have "to" in column A & "message/body" in column "B". I have a code which sends an email. However in my message I have a word hyperlinked to another sheet, while sending the email, the hyperlink is not considered. Please find the screenshot below.
However when the email is sent, the hyperlink is not visible. Please the image below
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 2);
var data = dataRange.getValues();
for (var i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var subject = 'Sending emails from a Spreadsheet';
MailApp.sendEmail(emailAddress, subject, message);
}
}
Use Templated HTML
var htmlBody = HtmlService.createTemplate('Email with <a href=<?=link?>> Some link </a>');
htmlBody.link = row[1];
MailApp.sendEmail({
to: row[0],
subject: 'Sending emails from a Spreadsheet',
htmlBody: htmlBody.evaluate().getContent()
});
If you have embedded cell links, you can extract them using Advanced Sheets services, as describe here, for example
var values = Sheets.Spreadsheets.get(SpreadsheetApp.getActive().getId(), {ranges: "Sheet1!B1:B10", fields: "sheets/data/rowData/values/hyperlink"})
var links = values.sheets[0].data[0].rowData.map(v => v.values[0].hyperlink);
them use them in templated HTML example I provided.
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);
}
}
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();
}
I have been trying to lookup username using activeuser. Only the first part works and the last part doesnt. My goal is to unhide the sheet based on the username of the active user (sheetname is based on username). Below is the code I am using.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [];
menuEntries.push({name: "Test getActiveUser/getEmail", functionName: "onTest"});
ss.addMenu("Rep Drowndown", menuEntries);
testGetEmail("onOpen");
}
function onTest() {
testGetEmail("menu function");
};
function testGetEmail(callerId) {
var userEmail = "";
var activeUser = Session.getActiveUser();
if (activeUser == null)
Browser.msgBox("Session.getActiveUser() returned null", "called by " + callerId, Browser.Buttons.OK);
else
userEmail = activeUser.getEmail();
if (userEmail == "")
Browser.msgBox("Your Email returned an empty string", "called by " + callerId, Browser.Buttons.OK);
else
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lookup = Session.getActiveUser().getEmail();
var range = ss.getRange('$A$3:$B$8').getValues();
var lookupRange = [];
for (var i = 0; i < range.length; i++)
lookupRange.push(range[i][0]);
var index = lookupRange.indexOf(lookup);
if (index == -1) {
// implicit no-op
}
else {
var link = range[index][2]
var sheet = ss.getSheetByName(link);
sheet.showSheet();
};
}
You need to set up an installable trigger. This allows the script to run with authorization, whereas normally "onOpen()" is run as a Simple Trigger. Since Simple Triggers can't authorize as users, you'll never get an email address.
The simplest solution is to set testGetEmail() to be run on open. Do this within the Script Editor by choosing Resources > Current Project's Triggers in the menu. Then click "No triggers set up. Click here to add one now." Finally, set up your trigger:
Choose your function's name (testGetEmail) from the first dropdown under "Run."
Choose "From spreadsheet" in the second dropdown under "Events."
Choose "On Open" in the third dropdown.
Then test to be sure I didn't commit a typo :-)