I am trying to create a simple script that does the following things:
whenever the document is opened, the script checks if a specific group is collapsed. If it isn't, it collapses it.
creates a custom menu that allows the user to toggle the appearance of said group - collapsing if it's expanded and vice versa.
Here's my logic - which doesn't seem to work for some reason:(
// Vars and stuff
let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0],
group = sheet.getColumnGroup(2, 1),
view_mode = group.isCollapsed(),
init = true;
// On/Off Functions
function view_mode_on() {
group.collapse();
view_mode = true;
SpreadsheetApp.flush();
};
function view_mode_off() {
group.expand();
view_mode = false;
SpreadsheetApp.flush();
};
// Toggle Function
function view_mode_toggle() {
Logger.log("This call runs when the function starts - view_mode: "+view_mode+", init: "+init);
if ( init == true ) {
init = false;
if ( view_mode == false ) {
view_mode_on();
}
} else {
view_mode == true ? view_mode_off() : view_mode_on();
};
Logger.log("This call runs when the function ends - view_mode: "+view_mode+", init: "+init);
}
// Open Function
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Testmenu')
.addItem('Toggle Edit Mode', 'view_mode_toggle')
.addToUi();
Logger.log("This call runs when the document is opened - view_mode: "+view_mode+", init: "+init);
view_mode_toggle();
}
I'm having a really hard time - the script seems to work unreliably: i think it collapsed the group sometimes, but that doesn't always happen. It never expanded the group. More than that, sometimes it prints logs in the console, while at times it doesn't. Lastly, it also seems to be very slow and I'm not sure if it's normal for these scripts to be so.
Any feedback would be greatly appreciated!
It seems you are overcomplicating things here.
isCollapsed()
is designed to check the state of a group column, not to set it. What you are trying to do with view_mode = false
just can't possibly work.Simple solution
Rewrite your script with the minimal amount:
function onOpen(e){
let ss = SpreadsheetApp.getActiveSpreadsheet();
let sheet = ss.getSheets()[0];
let group = sheet.getColumnGroup(2, 1);
group.collapse();
}
If you really must build your own toggle, then:
function toggle(){
let ss = let ss = SpreadsheetApp.getActiveSpreadsheet();
let sheet = ss.getSheets()[0];
let group = sheet.getColumnGroup(2, 1);
if (group.isCollapsed()){
group.expand();
}
else {
group.collapse();
}
}
and of course add this to your onOpen(e) function:
SpreadsheetApp.getUi()
.createMenu('Testmenu')
.addItem('Toggle Edit Mode', 'toggle')
.addToUi();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.