Search code examples
google-apps-scriptgoogle-slidespage-numbering

Slides is not defined


I'm doing my first steps in Google Apps script, and trying to add SlideNumbers with a code that I found. Each slide has textbox with "{{PgNm}}" text, and I'm trying to replace this with the pattern SlideNum/NumOfSlides. When I run it, I get "Slides is not defined" message. Maybe someone can help me?

function ReplacePgNm() {
 var MainPPT=SlidesApp.openById(MainPPT_ID);
 var Main=MainPPT.getSlides();
 var len = Main.length;

 var i = 1;

 Main.forEach(function(slide) {
    var pageElementId = slide.getObjectId();
    console.log(pageElementId);
    var resource = {
      requests: [{
        replaceAllText: {
          pageObjectIds: [pageElementId],
          replaceText: i+"/"+len,
          containsText: { matchCase: true, text: "{{PgNm}}" }
        }
      }]
    };

  Slides.Presentations.batchUpdate(resource, MainPPT.getId());
  i++;
  })
}

Solution

  • Modification points:

    • I think that the reason for your current issue of Slides is not defined is due to that you have never enabled Slides API at Advanced Google services.
    • And, in your script, Slides.Presentations.batchUpdate is used in a loop. In this case, the process cost becomes high.

    When these points are reflected in your script, it becomes as follows.

    1. Enable Slides API.

    Please enable Google Slides API at Advanced Google services.

    2. Modified script.

    function ReplacePgNm() {
      var MainPPT_ID = "###"; // Please set your Google Slides ID.
    
      var MainPPT = SlidesApp.openById(MainPPT_ID);
      var Main = MainPPT.getSlides();
      var len = Main.length;
      var requests = Main.map((slide, i) => ({
        replaceAllText: {
          pageObjectIds: [slide.getObjectId()],
          replaceText: (i + 1) + "/" + len,
          containsText: { matchCase: true, text: "{{PgNm}}" }
        }
      }));
      Slides.Presentations.batchUpdate({ requests }, MainPPT_ID);
    }
    

    Or, I thought that in your script, your goal can be achieved by only the Slides service (SlidesApp) without using Slides API. When this is reflected in a sample script, it becomes as follows. In this case, Slides API is not required to be enabled.

    function ReplacePgNm() {
      var MainPPT_ID = "###"; // Please set your Google Slides ID.
    
      var MainPPT = SlidesApp.openById(MainPPT_ID);
      var Main = MainPPT.getSlides();
      var len = Main.length;
      Main.forEach((slide, i) => slide.replaceAllText("{{PgNm}}", (i + 1) + "/" + len));
    }
    

    References: