I’m trying to get the middle initial from the middle name. Cell C12 in my script loads the middle name, while cell E12 loads the middle initial. To determine whether the text in cell C12 contains two words, I used the script chckWrd.includes(" ")
.
Example: Cell C12 is equals to “Dela Cruz”, cell E12 must load the text “DC” upon entering.
Then I used ‘chckWrd == “”‘ to determine whether cell C12 was empty. If it is empty, then cell E12 must likewise be empty.
The script runs fine, however it loads slowly. Is it possible to load it quickly or is there a shorter way for me to execute the script below?
function onEdit(e) {
var ss = e.source;
var cell = e.range;
// STUDENT MIDDLE NAME
if(cell.getA1Notation() === "C12" && ss.getActiveSheet().getName() == "UserForm"){
var myGoogleSheet= SpreadsheetApp.getActiveSpreadsheet(); //declare a variable and set with active google sheet
var shUserForm = myGoogleSheet.getSheetByName("UserForm"); //declare a variable and set with the User Form worksheet
var chckWrd = shUserForm.getRange("C12").getValue();
if (chckWrd == "") { // check if cell is empty
shUserForm.getRange("E12").clear();
shUserForm.getRange("E12").setBackground('#FFFFFF').setFontFamily('Roboto').setFontSize('12').setHorizontalAlignment("center");
} else { // check if cell is not empty
if (chckWrd.includes(" ")) { // check if cell includes space
var wordArray = shUserForm.getRange("C12").getValue().split(" ");
var first = wordArray[0].substring(0,1);
var second = wordArray[1].substring(0,1);
var middleInitial = first + second;
Logger.log(middleInitial);
shUserForm.getRange("E12").setValue(middleInitial);
} else { // middle name has one word
var wordArray = shUserForm.getRange("C12").getValue().substring(0,1);
var first = wordArray[0].substring(0,1);
Logger.log(first); // first word
shUserForm.getRange("E12").setValue(first);
}
}
}
}