如何编写Google Apps Script格式化Google幻灯片选中文本
Google幻灯片选中文本格式化脚本修正
你的代码问题出在直接对Selection对象调用文本格式化方法,getSelection()返回的是选中区域的对象,不能直接设置字体字号,得先提取具体的文本范围。另外你也没加左对齐的逻辑,下面是修正后的完整代码:
function onOpen() { const ui = SlidesApp.getUi(); ui.createMenu('Macros') .addItem('格式化选中文本', 'ParagraphFormat') .addToUi(); }; function ParagraphFormat() { const presentation = SlidesApp.getActivePresentation(); const selection = presentation.getSelection(); // 获取选中的文本范围 const textRange = selection.getTextRange(); if (textRange) { // 设置字体、字号 textRange.setFontFamily('Arial') .setFontSize(11); // 设置段落左对齐 textRange.getParagraphStyle() .setParagraphAlignment(SlidesApp.ParagraphAlignment.LEFT); } }
关键修正点:
- 先通过
getTextRange()从选中对象里提取可编辑的文本范围,只有存在选中文本时才执行格式化 - 调用
getParagraphStyle()来设置段落对齐方式,对应左对齐的枚举值是SlidesApp.ParagraphAlignment.LEFT - 增加了空值判断,避免没有选中文本时触发错误
内容的提问来源于stack exchange,提问作者Martin Bone
相关产品推荐
相关产品推荐

