Clear cell content when another cell is entered - javascript

Hi I'm very new to the google scripts, and would like to ask for your help.
In my spreadsheet, I need a script to clear data in cells I & J when a date is entered in cell H?
I.e. if a date is entered into H5, then clear all data in I5 & J5, or if a date is entered in H7 then clear all data in I7 & J7, etc.
Many Thanks

try that:
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("month test"); // don't forget to change by your sheet name
var statusValues = sheet.getRange("H:H").getValues();
for (var row in statusValues) {
try{
if(statusValues[row][0]!="" && typeof statusValues[row][0]=="object"){
var num = parseInt(row) + 1;
sheet.getRange(num, 9,1,2).setValue("");
}
}
catch(err){
Logger.log("didn't worked line: "+row+" --- "+err)}
}
};

Related

apps script, To view the message, please use an HTML compatible email viewer

I am trying to write a code that transfers data from gmail to spreadsheet. Here is the code:
function mailToStudio() {
var label = GmailApp.getUserLabelByName('GmailToStudio');
var threads = label.getThreads();
for (var i = threads.length - 1; i>=0; i--){
var msg = threads[i].getMessages()[0];
extractDetails(msg);
GmailApp.markMessageRead(msg);
}
}
function extractDetails(msg) {
var dateTime = msg.getDate();
var subjectText = msg.getSubject();
var senderDetails = msg.getFrom();
var body = msg.getPlainBody();
Logger.log(body);
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([dateTime, subjectText, senderDetails, body]);
}
My issue is with gmail body part. I want the data starting "Client Time" text and ending "Total" to be copied to spreadsheet in rows and columns same as given in gmail body.
Here is what I get:
1- When there are only few data lines in gmail body then the code works in such a way that it puts whole body content in a single cell instead of copying it to different rows and columns according to data structure.
2- When there are more data lines like 50+ lines in gmail body then the code does not work and all I get from body is an error "To view the message, please use an HTML compatible email viewer!".
Can anybody help how I can move gmail data to spreadsheet in proper rows and columns?
Thank you

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";
}
}
}
}

lookup username using getactiveuser using Google Spreadsheet script

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 :-)

Categories