[GAS Beginner Series #67] Format Slide Text and Font Size: Style “120% Achievement” Dynamically with TextRange.setText() & setFontSize()

When building monthly reports or executive presentations, you always want key performance figures and spotlight numbers to stand out immediately at a glance.

In our previous tutorial (Part 66), we explored how to programmatically place text boxes onto Google Slides using Slide.insertTextBox(). However, just creating an empty container isn’t enough to complete a report. To create a truly compelling slide, you need to populate it with concrete updates and boldly enlarge crucial metrics—like “120% Achievement”—to immediately draw the audience’s attention.

In this 67th installment of our series, we’ll dive deep into TextRange.setText() and TextRange.setFontSize(), the essential methods for taking full control of text inside your slides!

We will also address common beginner stumbling blocks, such as “Why did my font size reset after inserting text?” or “I wanted to enlarge just one specific phrase, but the entire text box grew huge!”—giving you solutions you can apply right away.

Once again using our Sapporo Office monthly performance presentation as our project canvas, let’s walk through this step-by-step with practical hands-on examples!

1. What Is TextRange? The Basic Structure of Slide Text Manipulation

When manipulating text on Google Slides with GAS, the key player responsible for reading, writing, and styling text is the TextRange object.

If you’re already familiar with Google Sheets or Docs, it helps to think of it much like a “Range” of cells or a “Paragraph.”

The Relationship Between Shapes, Text Boxes, and TextRange

Text on a slide always resides inside an outer container: a “Shape” or a “TextBox.”

[Slide]
   └── [TextBox / Shape (The outer frame)]
          └── [TextRange (The actual text content inside)] ★ This is where we insert text and change font size!

By calling getText() on the text box created in Part 66, you can grab the TextRange contained inside the frame.

// 1. Insert a text box onto the slide (creating the frame)
var textBox = slide.insertTextBox("Monthly Topics");

// 2. Extract the TextRange object from inside the frame to edit text!
var textRange = textBox.getText();

2. Two Key Methods to Master Today

Today’s focus is on mastering two primary methods called directly on a TextRange object.

① TextRange.setText("Your text here")

This method sets (inserts or replaces) the text string inside the specified TextRange.

textRange.setText("Sapporo Office monthly sales reached 120% of our target!");

② TextRange.setFontSize(points)

This method updates the font size of the specified TextRange in points (pt) as a numeric value.

// Change font size to 24pt
textRange.setFontSize(24);

3. STEP 1: Preparation! Set Up the “Sapporo Office Monthly Performance Report” Slide

Now let’s roll up our sleeves and write some code! We will build upon the slide presentation environment we set up across Parts 61 to 66.

Preparation Steps

  1. Create a new Google Slides presentation in Google Drive (or open the “Sapporo Office Monthly Performance Report Template” created in Part 61).
  2. Set the presentation title to “Sapporo Office Monthly Performance Report”.
  3. Copy the presentation ID from the URL (the string between https://docs.google.com/presentation/d/ and /edit).
  4. Click Extensions > Apps Script from the top menu to open the script editor.

4. STEP 2: [Hands-On] Inserting Topic Text and Resizing the Entire Content (Basics)

Let’s start with the basics: create a text box on the slide, populate it with descriptive text, and apply a clean, readable font size of 18pt across the whole text box.

Entering the Code

Clear out any default code in the Apps Script editor and paste the following snippet (make sure to replace YOUR_PRESENTATION_ID with your actual slide ID).

function setTopicsText() {
  // ① Retrieve the presentation and the first slide (Refer to Part 61)
  var presentationId = "YOUR_PRESENTATION_ID";
  var presentation = SlidesApp.openById(presentationId);
  var slide = presentation.getSlides()[0];
  
  // ② Place a text box for topics near the center of the slide (Refer to Part 66)
  // insertTextBox(text, left, top, width, height)
  var textBox = slide.insertTextBox("", 50, 150, 600, 150);
  
  // ③ Extract the TextRange object from the text box
  var textRange = textBox.getText();
  
  // ④ Populate the text content (setText)
  var reportText = "[Monthly Highlights]\nThanks to new project contracts won by the Sapporo Office, we achieved 120% of our company-wide target!";
  textRange.setText(reportText);
  
  // ⑤ Set the overall font size to 18pt (setFontSize)
  textRange.setFontSize(18);
  
  Logger.log("Topic text populated and font size updated successfully!");
}

Saving and Running

  1. Click the Save (disk icon) at the top of the editor.
  2. Confirm the function dropdown is set to setTopicsText, then click Run.
  3. Switch back to your slide: you should see your neatly formatted text rendered at 18pt at the specified coordinates!

5. STEP 3: [Advanced] Dynamically Highlight and Enlarge Only “120% Achievement”!

While our basic text insertion works nicely, presentation slides often need visual contrast to really make an impression.

Let’s take the key metric—“120% Achievement”—and make it jump off the slide with a massive 36pt bold font!

How Do You Style Just One Part of the Text?

If you’re thinking, “If I call setFontSize(36) on the TextRange, won’t the entire sentence blow up in size?”—don’t worry.

By using the TextRange.find("search text") method, you can pinpoint specific words and extract a targeted “sub-TextRange” representing just that matched portion!

// Search for '120% Achievement' within the full TextRange and grab it!
var matchedRanges = textRange.find("120% Achievement");

// Resize only the matched portion (index 0) to 36pt!
matchedRanges[0].setFontSize(36);

Hands-On Code (Partial Highlighting)

Add this advanced function to your script editor and run it.

function highlightPerformanceMetric() {
  var presentationId = "YOUR_PRESENTATION_ID";
  var slide = SlidesApp.openById(presentationId).getSlides()[0];
  
  // Insert a text box for the topic card
  var textBox = slide.insertTextBox("", 50, 100, 620, 200);
  var textRange = textBox.getText();
  
  // Set the report body text
  var content = "■ Sapporo Office Performance Topics\nThis month, contracts with 3 new clients were finalized, recording a 120% Achievement against departmental goals.";
  textRange.setText(content);
  
  // Set the default base font size to 16pt
  textRange.setFontSize(16);
  
  // 【Pro Technique】 Find and style only the key metric string!
  var targetPhrase = "120% Achievement";
  var matches = textRange.find(targetPhrase);
  
  // Apply styling if a match is found
  if (matches.length > 0) {
    var highlightRange = matches[0]; // Get the TextRange for the matched phrase
    
    // Enlarge the font size to 36pt!
    highlightRange.setFontSize(36);
    
    // Apply bold for extra emphasis (applying skills from Part 10!)
    highlightRange.setBold(true);
    
    // Set text color to an energetic accent red
    highlightRange.setForegroundColor("#D32F2F");
  }
  
  Logger.log("Dynamic styling for '120% Achievement' completed successfully!");
}

Verifying the Result

Open your slide, and you’ll notice the overall paragraph remains comfortably legible at 16pt, while “120% Achievement” pops out dramatically in 36pt bold red!

With just a few lines of code, you’ve created a polished performance card that looks like it was handcrafted by a graphic designer.

6. Quick Reference: Handy TextRange Properties & Methods

Here is a quick cheat sheet of frequently used TextRange methods for styling slide text.

Method Description Example
setText(text) Replaces the entire text content textRange.setText("Hello world")
setFontSize(pt) Sets the font size in points (pt) textRange.setFontSize(20)
setBold(boolean) Toggles bold styling on/off textRange.setBold(true)
setForegroundColor(hex) Changes the text color using a hex color code textRange.setForegroundColor("#1A73E8")
setFontFamily(font) Changes the font typeface textRange.setFontFamily("Roboto")
find(pattern) Searches for text and returns an array of ranges textRange.find("keyword")
clear() Clears all text inside the text box textRange.clear()

7. 5 Common Pitfalls Beginners Face (and How to Avoid Them)

Here are the five most frequent stumbling blocks developers encounter when working with slide text, along with how to solve them.

Trap 1: Calling shape.setText() and Triggering a TypeError

// ✕ Incorrect syntax
var textBox = slide.insertTextBox("Test");
textBox.setText("New text"); // TypeError: textBox.setText is not a function

[Cause & Solution]

setText() and setFontSize() are not methods of the text box (Shape) itself; they belong to the internal TextRange object.

Always call getText() first, such as textBox.getText().setText("...").

Trap 2: Calling setText() Resets All Prior Formatting!

// ✕ Incorrect execution order
textRange.setFontSize(36); // Resizing first
textRange.setText("New text"); // Setting text afterward ➡ Font size gets reset!

[Cause & Solution]

Because setText() overwrites the entire text content, it resets any existing font size or style configurations back to defaults.

Always follow this strict rule: 1. Populate text with setText() ➡ 2. Apply styling with setFontSize()!

Trap 3: Adding Unit Strings Like setFontSize("24pt")

// ✕ Incorrect
textRange.setFontSize("24pt"); // Throws an error

// ◯ Correct
textRange.setFontSize(24); // Pass a raw number

[Cause & Solution]

The argument for setFontSize() must be a pure Number, not a string with units like pt.

Trap 4: Forgetting that find() Returns an Array

// ✕ Incorrect syntax
var match = textRange.find("120% Achievement");
match.setFontSize(36); // TypeError: match.setFontSize is not a function

[Cause & Solution]

Because there could be multiple instances matching your keyword, find() returns an array of TextRange objects ([]).

To style the first occurrence found, specify the index like match[0].setFontSize(36).

Trap 5: The Script Crashes When find() Yields No Matches

If the searched string does not exist in the text, matches will be an empty array [].

Attempting to run matches[0].setFontSize(36) directly will throw an error because matches[0] is undefined.

Writing robust, production-ready code means always guarding your logic with an if (matches.length > 0) { ... } check.

8. Summary & What’s Next

In this guide, we covered how to populate Google Slide text using TextRange.setText() and adjust typography on demand with TextRange.setFontSize().

Key Takeaways for Today

  1. Always retrieve the TextRange using textBox.getText() before editing text!
  2. Follow the standard sequence: setText("content") first, then setFontSize(number)!
  3. To enlarge specific phrases, use textRange.find("phrase")[0] to target that sub-range!
  4. Pass numbers directly to setFontSize(36) without adding “pt” string units!

Now you have the tools to highlight the most important metrics in your presentations automatically and with maximum visual impact!

Once you’ve showcased key highlights with topic cards, the next thing you’ll naturally want on your slides is clean, structured tables detailing revenue and cost trends across projects.

In our next article (Part 68), we will explore Slide.insertTable() to automatically generate polished, well-formatted tables directly on your slides!