I have a question similar to this one.
Change Google Spreadsheets cell horizontal alignment using python
My sample sheet
The sample sheet was inspired by this Youtube Tutorial
uses a QUERY
formula (in the 'Report' sheetA5
) dependant on 2 validation dropdowns (in cells A2 and B2).
I'd need the script to horizontally center align all the Uppercase cells and only the Uppercase cells in the range A5:B
.
And it needs to do it dynamically, on the change event (when I switch the dropdown selection in A1
and/or B1
).
I tested this from gathered other solutions and documentation below but it's not working.
function onEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetByName = e.sheet.getSheetByName("Report");
var range = e.sheetByName.getRange('A5:B');
var value = e.range.getValue();
const isUpperCase = (string) => /^[A-Z]*$/.test(string)
if (sheetByName === 'Report' &&
typeof value === 'string' &&
isUpperCase(value)) {
e.range.setHorizontalAlignment("center");
}
}
I also tested with this other script but not success:
function onEdit(e){
const sh = SpreadsheetApp.getActiveSheet();
const isUpperCase = (string) => /^[A-Z]*$/.test(string)
e.sh.getRange(5, 1, sh.getLastRow()-1, 2).getValues().flat().forEach((v, i) => {
if (isUpperCase(v)) {
e.sh.getRange(1, i + 1).setHorizontalAlignment("center");
}
});
}
My test was from insights from those other answers.
Google Sheets macro to center align all dashes in top row
How can I test if a letter in a string is uppercase or lowercase using JavaScript?
How to uppercase a cell range even if user type or paste lowercase with no warning in Google Sheet
Script to automatically capitalize contents of a cell in Google Sheets?
Many thanks in advance for your help!