In GDocs under Tools > Preferences, I can define automatic corrections, so that if I type l*
, it spells low, h*
-> high, etc.
In Google Spreadsheet there is nothing like that. Can I do that with script? How?
Web Applications Stack Exchange is a question and answer site for power users of web applications. It only takes a minute to sign up.
Sign up to join this communityAs Eddy told you, it can be done by using the onEdit trigger.
//global
var ss = SpreadsheetApp.getActiveSpreadsheet();
var name = "Preferences";
function onEdit(e) {
// clear cache if on preferences sheet
if(ss.getActiveSheet().getName() == name) {
CacheService.getPrivateCache().remove(name)
} else {
// get all the data
var prefs = JSON.parse(preferences());
var cValue = e.value, cRange = e.range;
var pref = cValue.match(/\b[a-z]+\*\B/);
// find replacement text
for(var i=1, iLen=prefs.length; i<iLen; i++) {
if(pref == prefs[i][1] && prefs[i][0] == "Yes") {
var text = prefs[i][2];
}
}
// make the change
if(text.length == cValue.length) {
cRange.setValue(prefs[i][2]);
} else {
var modcValue = cValue.replace(pref, text);
cRange.setValue(modcValue);
}
}
}
function preferences() {
// check if cache is available
var cache = CacheService.getPrivateCache();
var cached = cache.get(name);
if (cached != null) {
return cached;
}
// collect data
var data = ss.getSheetByName(name).getDataRange().getValues();
var jsonData = JSON.stringify(data);
cache.put(name, jsonData, 21000);
return jsonData;
}
The script will first check if the preference sheet has been modified. If yes
, then it will clear/remove the cache. After that, it will either retrieve all the data from the references sheet or the cache. Then it will determine which shortcut is to be used, by means of the match
and regex
. If the criteria are met, the With column value will be added.
Copy the spreadsheet I've prepared and look under Tools, Script editor. There you will find the script. Press the bug button to validate/authenticate the script.
I've created an example file for you: Script to automatically change text value
*
. Multiple leading characters are allowed (see example).The regex, to match the replacement text, was all wrong. Added possibility to change the replacement text from within sentence.
The onEdit trigger would do it. https://developers.google.com/apps-script/understanding_events
But, it would change only after you press enter. So it would run after you finish editing the cell, not while you are editing.