When creating heading levels in a document, it's easy to get confused about which level a paragraph should be at. If you reduce a header level, the headings below need to be adjusted also, and its not till you come to creating a contents page that you notice it's all out of line. Here's a snippet to adjust header levels so that sub headings are never more than one deeper than the previous header. Adjusting heading levelsThis one provides a dry run capability, where the log file tells you what it would have done. Set it to false when you are ready to go for real. The code// sometimes header levels get screwed up and need to be readjusted // this will ensure that a header level is never more than one higher than the one before it function workHeaderLevels () { var doc = DocumentApp.getActiveDocument(); // set this to false when it looks like it does what's needed var DRY_RUN = true; // these are the only ones to be considered var heirarchy = [ DocumentApp.ParagraphHeading.HEADING1, DocumentApp.ParagraphHeading.HEADING2, DocumentApp.ParagraphHeading.HEADING3, DocumentApp.ParagraphHeading.HEADING4, DocumentApp.ParagraphHeading.HEADING5, DocumentApp.ParagraphHeading.HEADING6 ]; doc.getBody().getParagraphs().reduce (function (p,c) { var heading = c.getHeading(); var idx = heirarchy.indexOf(heading); // check it's an interesting one if (idx !== -1) { if (idx > p+1) { p++; Logger.log( (DRY_RUN ? 'would have adjusted ' : 'adjusting ') + c.getText().slice(0,10) + ' from ' + heading + ' to ' + heirarchy[p]); // really do it if (!DRY_RUN) { c.setHeading (heirarchy[p]); } } else { p = idx; } } return p; },-1); } For more like this, see Google Apps Scripts snippets. Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.You want to learn Google Apps Script?Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly. If you prefer Video style learning I also have two courses available. also published by O'Reilly. |
Services > Desktop Liberation - the definitive resource for Google Apps Script and Microsoft Office automation > Google Apps Scripts snippets >