You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 11:05:26