PowerPoint's programming model centers around two objects: Shape and TextRange. Although Word and Excel each provide a Shapes collection object that is consistent with PowerPoint's Shapes collection object, shapes aren't the main content type in these two applications: text and cells are, respectively. In PowerPoint, the Shape object is vital because all content in a presentation, including text, exists in a shape. Even if a slide has nothing but text, the text is contained in a shape of a specific type.
To access text, first you have to access the shape in the Shapes collection object on a slide, and then access the text in a shape using the TextRange object. The TextRange object represents a continuous area of text within a shape. The TextRange object, which is very similar to and nearly as robust as Word's Range object, allows you to retrieve or set text, as well as apply formatting to text, in any shape in a presentation. You can only access the TextRange object by first accessing a shape.
TIP
The code listed here that describes how to insert and manipulate presentation content in PowerPoint is also found in the PpContnt.bas code module in the Chapter 6 practice folder on the CD that comes with this book.
Each slide in a PowerPoint presentation contains a Shapes collection. To access a Shapes collection, you first need to access a specific slide in a presentation's Slides collection. A shape represents any object on a slide, including a text box, an AutoShape, an OLE object, a picture, a table, or a chart. You can access a Shape object using the Shapes collection or the ShapeRange collection. The Shapes collection represents all shapes on a slide, and a ShapeRange collection can represent all or a subset of shapes on a slide. As you'll see in this section, the ShapeRange collection is useful in cases where formatting is applied to multiple shapes.
The ShapeRange collection object usually consists of a subset of shapes that exist in the Shapes collection for a particular slide. When you work with selected shapes in the active window, you'll commonly work with the ShapeRange collection. Users generally select multiple shapes and apply settings to the shapes in the selection. Before running the following procedure, insert a number of different shapes on the slide in the active window, such as a rectangle, ActiveX control, line, WordArt, and text box. Then select all shapes and run the following procedure from a module in the Visual Basic Editor in PowerPoint:
Sub SetShapeProperties() If ActiveWindow.Selection.Type <> _ ppSelectionShapes Then Exit Sub With ActiveWindow.Selection.ShapeRange With .Fill .ForeColor.RGB = RGB(255, 0, 102) .OneColorGradient Style:=msoGradientHorizontal, _ Variant:=2, Degree:=0.23 End With .Line.ForeColor.RGB = RGB(200, 100, 150) With .TextFrame.TextRange With .Font .Name = "Arial" .Size = 24 .Bold = msoTrue .Color.RGB = RGB(255, 255, 0) End With End With End With End Sub |
The preceding procedure sets properties such as fill color, fill gradient, line border color, and font attributes to the selected shapes. Although some properties may not apply to specific shapes in the selection, using the ShapeRange collection object saves you from having to filter which shapes certain properties don't apply. Therefore, you can write your code generically and PowerPoint will determine if the property can or can't be applied to a specific shape in the ShapeRange collection. This is the same as the course of action in PowerPoint when you select a number of different types of shapes on a slide and click on the Fill Color button on the Drawing toolbar or the Bold button on the Formatting toolbar.
In some cases, you may want to iterate through the selected shapes, and apply property settings only to a specific shape. The following procedure determines if the slide title shape is in the selection of shapes in the active window. If the slide title shape is in the selection, the procedure positions the title shape back to specific left and top coordinates. You can change the code within the nested If…Then block to set or retrieve any property of the title shape.
Sub CheckIfShapeExistsInShapeRange() Dim shp As Shape If ActiveWindow.Selection.Type <> _ ppSelectionShapes Then Exit Sub For Each shp In ActiveWindow.Selection.ShapeRange If shp.Type = msoPlaceholder Then If shp.PlaceholderFormat _ .Type = ppPlaceholderTitle Then shp.Left = 53.5 shp.Top = 36 End If End If Next shp End Sub |
This example uses the objects and properties associated with placeholders to determine if a specific shape is found on a slide or in a selection. Placeholders are described after the following example.
You can extend the previous example and make it more robust. To do so, set the left and top coordinates of the slide title shape to the default position of the title shape on the slide master of the presentation. This procedure is useful in scenarios where you may want to reset the position of a placeholder, such as the slide title, back to its default coordinates (based on the slide master).
Sub WorkingWithSlideMaster() Dim shp As Shape, sldMaster As Master If ActiveWindow.Selection.Type <> _ ppSelectionShapes Then Exit Sub For Each shp In ActiveWindow.Selection.ShapeRange If shp.Type = msoPlaceholder Then If shp.PlaceholderFormat _ .Type = ppPlaceholderTitle Then Set sldMaster = ActiveWindow.View.Slide.Master With sldMaster.Shapes _ .Placeholders(ppPlaceholderTitle) shp.Left = .Left shp.Top = .Top End With End If End If Next shp End Sub |
You can view the master for the slides in the presentation by clicking Master on the View menu and then selecting Slide Master from the submenu in PowerPoint. In the preceding procedure, you declare the variable sldMaster as a Master object. It's set to the master of the slide in the active window. The slide title shape's coordinates are set to the coordinates of the title shape on the slide master.
Because the nested If…Then only looks for the placeholder of type ppPlaceholderTitle, the sldMaster will always be set to the master that's in view when you click Slide Master on PowerPoint's Master submenu. If the slide layout is a title slide (see the discussion on slide layout later in the chapter), the slide title shape would be of the placeholder type ppPlaceholderCenterTitle.
Placeholders are special kinds of shapes specific to PowerPoint and aren't found in Word's or Excel's Shapes collection. Placeholders are tied to the layout of a slide. For example, you commonly insert slides with either the title layout or, more commonly, the body layout. The body layout has both a title placeholder and a body placeholder. When you work with text and insert new slides in Outline view, slides are created with the body layout by default.
Using placeholders, you can access shapes like the slide title or body placeholder shape no matter where the placeholder shape is in the collection. When you change the z-order of a shape on the slide, the index position of a placeholder or any other shape in the Shapes collection changes. As a result, it's easier to use in your code the Placeholders collection, accessed from the Shapes collection, to access the most common shape elements on a slide.
Sub InsertSlideAndAccessPlaceholders() Dim sldNew As Slide Set sldNew = ActivePresentation.Slides _ .Add(Index:=1, Layout:=ppLayoutText) With sldNew.Shapes .Placeholders(1) _ .TextFrame.TextRange.Text = "Ideas..." .Placeholders(2) _ .TextFrame.TextRange.Text = "Use VBA." With .AddShape(msoShapeCloudCallout, _ 50, 50, 120, 100) .TextFrame.TextRange.Text = "Thoughts?" End With End With End Sub |
This procedure inserts a new slide with the layout ppLayoutText. This layout represents a slide with the title and body placeholders. You then use the Placeholders collection to insert text in the title and body placeholders. The procedure adds a new AutoShape and positions it near the top left of the body placeholder.
To retrieve the main text in a presentation, you usually need to access the title and body placeholder on a slide. Some slides, however, may not have the title or body placeholder. And because there are up to 16 different placeholder PpPlaceholderType constants that represent the possible placeholder types, you may also be searching for other placeholders on a slide. The three procedures listed in this section work together to iterate through the slides in the active presentation and retrieve the slide title and body placeholder text, if either exists. They print the retrieved text to a text file under the Temp folder on the C: drive. You can change the file path "C:\Temp" to an appropriate path on your machine.
In this example, the procedure sends the content of a PowerPoint presentation to a text file, but you can use the content of a PowerPoint presentation to be the basis of a new Word document. This functionality is similar to pointing to Send To on the File menu and then clicking Microsoft Word on the submenu in PowerPoint. Chapter 7 describes the reverse operation; that is, you use a Word document as a basis for creating a new PowerPoint presentation.
The first of the following three procedures is the main one. You set the variable sOutputFile to the output text file and use the Open statement to open the text file in Output mode. The Output mode indicates that if the file exists on disk, its content will be overwritten. The For Each…Next loop iterates through each slide in the presentation. The first line within the For Each…Next loop prints the slide title in the text file. The procedure retrieves the slide title by using the function SlideTitle. The section "Iterate Through Titles in a Presentation" later in this chapter describes the SlideTitle function.
Sub PrintContentsOfPresentationToTextFile() Dim sld As Slide, shpBodyPlaceHolder As Shape Dim iFreeFile As Integer, sOutputFile As String sOutputFile = "C:\Temp\ActivePresentationText.txt" iFreeFile = FreeFile Open sOutputFile For Output As iFreeFile For Each sld In ActivePresentation.Slides Print #iFreeFile, SlideTitle(sld) If PlaceholderExists(sld.Shapes, _ ppPlaceholderBody, shpBodyPlaceHolder) Then Print #iFreeFile, shpBodyPlaceHolder _ .TextFrame.TextRange.Text End If Print #iFreeFile, Next sld Close #iFreeFile ' ShellExecute 0, "Open", sOutputFile, "", "", 1 End Sub Function PlaceholderExists(shpColl As Shapes, _ iType As PpPlaceholderType, _ shpPlaceHolder As Shape) As Boolean For Each shpPlaceHolder In shpColl.Placeholders If shpPlaceHolder.PlaceholderFormat.Type = iType Then PlaceholderExists = True Exit Function End If Next shpPlaceHolder End Function Function SlideTitle(sld As Slide) As String Dim sPrefix As String, sSlideTitle As String If sld.Shapes.HasTitle Then sSlideTitle = sld.Shapes.Title.TextFrame.TextRange.Text End If sPrefix = sld.SlideNumber & ". " If Len(sSlideTitle) Then SlideTitle = sPrefix & sSlideTitle Else SlideTitle = sPrefix & "Slide " & sld.SlideNumber End If End Function |
After the slide title is retrieved, the If…Then block in the first procedure then uses the PlaceholderExists function to determine if the body placeholder exists. Because this function is generic, you can use it to determine if any placeholder exists. You need to pass three arguments to the function. The first is the Shapes collection of the slide you want to search on for a specific type of placeholder; the second is the placeholder type you want to search for; and the third is an object declared as type Shape. If the PlaceholderExists function finds the specified placeholder type, the procedure sets the object variable shpPlaceholder to the placeholder. If the placeholder exists, the procedure prints the text contents in the body placeholder to the output text file, followed by a blank line.
Copy the three preceding procedures in a code module in the Visual Basic Editor in PowerPoint, switch back to PowerPoint, and click New on the File menu. In the Presentations tab, select a presentation that's installed on your machine. Click OK. Switch back to the Visual Basic Editor and run the PrintContentsOfPresentationToTextFile procedure. Navigate to the output text file in the Microsoft Windows Explorer to see the results.
You can extend the preceding example to automatically open the text file after it's been closed for output. This is the same operation you saw in Chapter 4, where the program automatically opens the HTML document saved to disk in the Web browser installed on your machine. The last line in the first procedure in the preceding example contains the following line, which is commented out:
ShellExecute 0, "Open", sOutputFile, "", "", 1 |
Remove the comment from the beginning of the line, and then add the following Windows API to the top of the code module:
Declare Function ShellExecute Lib "shell32.dll" _ Alias "ShellExecuteA" ( _ ByVal Hwnd As Long, _ ByVal lpOperation As String, _ ByVal lpFile As String, _ ByVal lpParameters As String, _ ByVal lpDirectory As String, _ ByVal nShowCmd As Long _ ) As Long |
Run the PrintContentsOfPresentationToTextFile procedure again. This time, the output text file should be opened and displayed in Microsoft Notepad. You can use this functionality in any scenario, no matter where you write Visual Basic code.
As discussed earlier in this chapter, PowerPoint's content breakdown is similar to Excel's. Excel organizes content in worksheets, and PowerPoint uses slides. In PowerPoint, the Slides collection allows your code to iterate through and work with specific slides in a presentation. You can also use the Slides collection object to add a new slide and, hence, new content.
The following procedure iterates through slides in the Slides collection object. The procedure assigns each slide to the variable sld and prints the slide name, number, and index to the Immediate window in the Visual Basic Editor in PowerPoint.
Sub IterateThroughSlides() Dim sld As Slide For Each sld In ActivePresentation.Slides Debug.Print "Slide name: " & sld.Name Debug.Print "Slide number: " & sld.SlideNumber Debug.Print "Slide Index: " & sld.SlideIndex Next sld End Sub |
By default, PowerPoint gives a new name to each slide created, although there's no way to change a slide's name through the menus, toolbars, or dialog boxes. You can only do that by setting the Name property through Visual Basic code. You can also use the value returned by the Name property as the index argument in the Slides(index) property on the Presentation object so that your code can return a specific Slide object.
The SlideIndex property returns a number representing the position of the slide in the Slides collection. The SlideIndex number is directly related to the position of the slide on screen. The Name property returns the name of the slide. The SlideNumber property on the Slide object returns the slide number visible on the slide. You can set the slide number in PowerPoint by selecting the Slide number check box in the Slide tab of the Header and Footer dialog box. You can access this dialog box by clicking Header and Footer on the View menu.
You use the Add method of the Slides collection to insert a new slide in the presentation. The Add method takes two arguments, Index and Layout, and you need both. The Index argument represents the position of the new slide in the Slides collection. If you want to add the slide to the end of the Slides collection, you need to set the Index argument to the number of the slides in the collection plus one. The code would appear as:
With ActivePresentation.Slides Set sldNew = .Add(Index:=.Count + 1, _ Layout:=ppLayoutText) End With |
If you want to insert a new slide at the end of the Slides collection, replace the Set sldNew statement in the following procedure with the With…End block above.
Sub InsertSlide() Dim sldNew As Slide Set sldNew = ActivePresentation.Slides _ .Add(Index:=1, Layout:=ppLayoutText) With sldNew .Shapes(1).TextFrame.TextRange.Text = "Ideas..." .Shapes(2).TextFrame.TextRange.Text = "Use VBA." With .Shapes.AddShape(msoShapeCloudCallout, _ 50, 50, 120, 100) .TextFrame.TextRange.Text = "Thoughts?" End With End With End Sub |
The Layout argument allows your code to specify the slide layout for the new slide. Every slide in PowerPoint has a slide layout. You need to set a Layout argument to a PpSlideLayout constant. When you insert a new slide in PowerPoint by clicking New Slide on the Insert menu in PowerPoint's application window, the New Slide dialog box displays all the possible slide layouts. The name of the layout appears at the right in the dialog box. Most layout names in the dialog box are similar to their associated PpSlideLayout constant. In the preceding procedure, the PpSlideLayout constant ppLayoutText represents the Bulleted List layout in the New Slide dialog box.
A slide's title and body placeholder are two elements you'll commonly find on slides. The slide title is commonly used to display a list of Slides in a presentation. The following procedure allows you to return a list of slide titles exactly like the list you'll find in the Slide Navigator in Slide Show. In Slide Show view, right-click on the slide, click Go, and click Slide Navigator on the submenu.
You can also see a list of slide titles in the Insert Hyperlink dialog box by clicking Hyperlink on the Insert menu and then selecting Place in This Document on the Link To bar at the left of the dialog box. In the Visual Basic Editor in PowerPoint, run the following procedure. The list of slide titles is printed in the Immediate window.
Sub RetrieveSlideTitleList() Dim sld As Slide Dim sPrefix As String, sSlideTitle As String For Each sld In ActivePresentation.Slides If sld.Shapes.HasTitle Then sSlideTitle = sld.Shapes.Title _ .TextFrame.TextRange.Text End If sPrefix = sld.SlideNumber & ". " If Len(sSlideTitle) Then Debug.Print sPrefix & sSlideTitle Else Debug.Print sPrefix & "Slide " & _ sld.SlideNumber End If Next sld End Sub |
PowerPoint provides a shortcut that allows you to easily determine if a slide title exists and if so, to access the title shape. Instead of using the Shapes(Index) property on the Slide object or the Placeholders(Index) property on the Shapes collection object to return the slide title, you can use the Title property on the Shapes object. This property provides a shortcut to the Title shape.
Even though the majority of slides have a slide title, some may not. Either the slide layout is blank (ppSlideLayoutBlank) or the user deleted the slide title shape. Therefore, before you access the slide title shape using the Title property on the Shapes object, your code should first use the HasTitle property. If the slide does have a title, the string variable sSlideTitle is set to the text of the slide title shape. The If…Then…Else block determines if the length of text assigned to the variable sSlideTitle is greater than zero. If so, the procedure prints the slide title to the Immediate window. If not, it prints the slide number to the Immediate window.
In a PowerPoint presentation, all text has to exist in a shape. The TextRange object allows you to insert or manipulate text content in a shape. You can set the TextRange object so that it represents all or only a portion of a range of text. A TextRange object can consist of text that represents a single paragraph (a bulleted list item, for example) or all text in a shape (such as all bulleted items).
Within every TextRange object, you can return more granular units of text—just as you can in Word with the Range object. The TextRange object allows you to iterate through units of text as large as all the text in a shape and as small as a paragraph (usually a bulleted item), a sentence, a word, and, finally, a character. The TextRange object in PowerPoint is equivalent in purpose to the Range object in Word. Many methods and properties on both of these objects are similar as well.
You can't apply a number of properties on the Shape or ShapeRange object to all shapes. You can use the Paragraphs, Sentences, Words, or Character properties on the TextRange object to return the collection of paragraphs, sentences, words, or characters from a range of text. However, you can't access the text range on shapes like a line, WordArt, bitmap placeholder, or ActiveX control. Before you try to access text in a range of shapes—in a selection, for example —you need to determine if a shape can contain text.
To access text, you need to first access the TextFrame object. In hierarchical object terms, a Shape object contains a TextFrame. The TextFrame contains a TextRange object that actually represents text. Some shapes don't contain a TextFrame object. To determine if a shape does contain one, and therefore can contain text, you can use the HasTextFrame property on the Shape object. Thereafter, if a shape does contain text, you can access the text in the shape and set its properties.
Sub IterateParagraphsAndSetBullets() Dim para As TextRange Dim shp As Shape, iCount As Integer If ActiveWindow.Selection.Type <> _ ppSelectionShapes Then Exit Sub For Each shp In ActiveWindow.Selection.ShapeRange If shp.HasTextFrame Then iCount = 0 For Each para In shp.TextFrame _ .TextRange.Paragraphs If para.IndentLevel = 1 Then With para.ParagraphFormat.Bullet If .Type <> ppBulletNone Then .Font.Name = "Arial" .RelativeSize = 0.75 iCount = iCount + 1 .Character = 48 + iCount End If End With End If Next para End If Next shp End Sub |
Before running this procedure, insert different shapes on the active slide, such as a line, an ActiveX control, some WordArt, and a rectangle. Add text to the rectangle, the title, and the body placeholder, if they exist. Select all shapes on the slide and then run the procedure. Make sure that the body text is bulleted. The procedure determines if the selection in the active window is a range of shapes. If so, the first For Each…Next loop iterates through the shapes in the selected shape range. If the shape contains a text frame, the nested For Each…Next loop iterates through the paragraphs in the text range of the selected shape.
The If…Then statement evaluating the bullet Type property is used to determine if there is a bullet visible for the paragraph. If there is, then the For…Each loop proceeds to add a number as the bullet. If a bullet does not exist, the bullet of the paragraph is unaffected. Every bulleted item in a shape, including those that are indented below a main bulleted item, is considered a paragraph. You access the list of bulleted items by using the Paragraphs property on the TextRange object. The Paragraphs property returns the collection of paragraphs in the text range of a shape. You can use the IndentLevel property to return specific paragraphs in a shape. The preceding procedure sets the bullet character to a number if the bullet exists for the paragraph. This procedure mimics the functionality of automatically numbering bulleted items in a shape.
Unlike in Word, in PowerPoint your code can only navigate down the text "hierarchy" tree. For example, if you select a bulleted item on a slide in the active window, you can access the sentence, word, and character collections in the bulleted item. However, if you had selected a word, you cannot return the sentence or paragraph the word belonged to. The Range object in Word, on the other hand, allows you to return the paragraph where a range of text, such as a word, is contained.
The following procedure prints to the Immediate window in the Visual Basic Editor in PowerPoint the first paragraph, sentence, and word of a text selection. For example, in a body placeholder on a slide, type in two bulleted items where the first item has two or more sentences. Select all of the text in the shape and then run the following procedure in a module in the Visual Basic Editor.
Sub NavigateDownTextHierarchy() Dim rng As TextRange If ActiveWindow.Selection.Type = ppSelectionText Then Set rng = ActiveWindow.Selection.TextRange Debug.Print rng.Paragraphs(1) Debug.Print rng.Sentences(1) Debug.Print rng.Words(1) End If End Sub |
PowerPoint is similar to Word in that a unit of text representing a word consists of the text of the word followed by the space between the text and the next word. If you double-click on a word in a Word document or in a shape in PowerPoint, the text and the space after the text is highlighted. The same principle holds for sentences. A sentence in Word and PowerPoint consists of the sentence's text followed by the space between the period and the next sentence. A paragraph includes the text, space after the end of the text (if any), and the paragraph marker.
Sub SpaceAfterTextUnits() Dim rng As TextRange If ActiveWindow.Selection.Type = ppSelectionText Then Set rng = ActiveWindow.Selection.TextRange Debug.Print rng.Words(1) & Chr(34) Debug.Print rng.Words(1).TrimText & Chr(34) Debug.Print rng.Sentences(1) & Chr(34) Debug.Print rng.Paragraphs(1) & Chr(34) End If End Sub |
Before running this procedure, add text to a body placeholder and add two sentences to the first bulleted item. Select all text in the bulleted item and run the procedure. The procedure prints the text of the first word, sentence, and paragraph (which represents the bulleted item) to the Immediate window, followed by a quote. Chr(34) represents the quote character ("), which allows you to see the spaces after each unit of text.
Unlike in Word, in PowerPoint you can use the TrimText property to remove all spaces and paragraph markers before and after a unit text. The built-in Trim$ function in the Visual Basic for Applications language works only for removing spaces before and after a text string. The TrimText property in PowerPoint also removes paragraph markers after, for example, a sentence or paragraph. The TrimText property is useful when you retrieve the last paragraph in a shape and don't want the paragraph marker along with the text.
When you build presentation content programmatically, you commonly have to insert paragraphs. PowerPoint, like Word, provides two convenient methods for creating a new paragraph before or after an existing one: InsertBefore and InsertAfter. When you access a range representing an existing paragraph or the beginning or end of one, you can use either of these two methods to insert a new paragraph.
The following procedure assumes that the active presentation contains at least two slides and two shapes on the second slide. The procedure also assumes that the second shape on the second slide has at least two bulleted items. The code inserts a new paragraph at the end of the text range in the shape using the InsertAfter method on the TextRange object. The InsertAfter method takes one argument representing the new text to be added in the new paragraph. This procedure adds a new paragraph after the first paragraph in the shape. Note that in the text string assigned to the variable sNewPara, a carriage return, represented by Chr(13), is added to the end of the text. When the text string is set to the new paragraph, the carriage return ensures that the new paragraph is separate from the paragraph after the new paragraph.
Sub InsertNewParagraphBetweenParagraphs() Dim shp As Shape, rngText As TextRange Dim sNewPara As String sNewPara = "New paragraph between items." & Chr(13) Set shp = ActivePresentation.Slides(2).Shapes(2) With shp.TextFrame.TextRange.Paragraphs(1) Set rngText = .InsertAfter(NewText:=sNewPara) rngText.Font.Italic = msoTrue rngText.IndentLevel = 2 End With End Sub |
Another very common task in programming solutions is to insert content at the end of text in the body placeholder or any shape. The following procedure inserts text at the end of a text range using the InsertAfter method. However, in this case it adds the carriage return character at the beginning of the text string assigned to the string variable sNewPara.
Sub InsertNewParagraphAtEndOfTextRange() Dim shp As Shape, rngText As TextRange Dim sNewPara As String sNewPara = Chr(13) & "New paragraph." Set shp = ActivePresentation.Slides(2).Shapes(2) With shp.TextFrame.TextRange Set rngText = .InsertAfter(NewText:=sNewPara) rngText.Font.Italic = msoTrue End With End Sub |
PowerPoint 2000 is the first version of PowerPoint that offers a way of creating tables that's similar to the functionality provided by the Draw Table command on Word's Tables And Borders toolbar. The following two procedures create a simple five-row by three-column table. They create the table on a new slide inserted at the end of the Slides collection in the active presentation. You should note that your code can insert a table that has up to 25 rows and 25 columns. This is also the row and column limit that's set when you create the table using the Tables And Borders toolbar.
First you set the new table to the Table variable tbl. PowerPoint doesn't provide the ability to apply predefined formats to your table as Word does using the Table AutoFormat on the Table menu. Since you can't format a table with a preset table format, you need to explicitly format the table through code. You do this by using the SetTableFormatting procedure. You call the procedure InsertTableData to fill the second and third columns with random values after you apply formatting.
As described in this chapter's Word and Excel table examples, you could, for example, replace the code in InsertTableData with code that accesses data in an Access database.
NOTE
The result of the table appears in the following graphic. Note the formatting applied to specific sets of cells. For example, the text in the first row is bold and italicized. The text in the first column is left aligned, while the text in the second and third columns is center aligned.
NOTE
The code to create this table is listed below and is also found in the PpContnt.bas code module under the Chapter 6 practice folder on the CD that comes with this book. Also note that the first two lines in the code belong at the top of the standard code module. If Option Explicit is already listed at the top of your code module, you do not need to type it again. However, the module-level variable, m_sldSales, is used in the other procedures listed below.
Option Explicit Dim m_sldSales As Slide Sub InsertTable() Dim tbl As Table Dim iNumOfRows As Integer, iNumOfColumns As Integer ' create new slide and add title text With ActivePresentation Set m_sldSales = .Slides.Add( _ Index:=.Slides.Count + 1, _ Layout:=ppLayoutTitleOnly) End With m_sldSales.Shapes.Title.TextFrame _ .TextRange = "Q2 Sales: Increase (%)" ' insert table iNumOfRows = 5: iNumOfColumns = 3 Set tbl = m_sldSales.Shapes.AddTable(iNumOfRows, _ iNumOfColumns, 54, 156, 612, 324).Table SetHeadingRowText tbl SetFirstColumnText tbl InsertTableData tbl End Sub Sub InsertTableData(tbl As Table) ' fill cells with random data Dim x As Integer, y As Integer For x = 2 To tbl.Rows.Count For y = 2 To tbl.Columns.Count tbl.Cell(x, y).Shape.TextFrame.TextRange _ .Text = Format$(Rnd(), "###0.00") Next y Next x End Sub |
IMPORTANT
When you select a set of cells in a table on a slide and click on the Bold button on the Formatting toolbar, for example, PowerPoint applies formatting to all cells in the selection. However, PowerPoint doesn't allow you to mimic the same behavior through code. You have to explicitly create a shape range of cells and apply formatting to the set of cells. The code provides a good structure to apply formatting to a specific set of cells in a table. The remaining procedures are called from the preceding SetTableFormatting procedure.The GetRowArray, GetColumnArray and GetTableCellArray procedures return an array used to create a collection of shapes within a ShapeRange object. Using the ShapeRange object, you can apply formatting to all cells at once. The GetRowArray and GetColumnArray procedures are designed to allow your code to specify what row or column of table cells should be returned as a shape range. The procedures also allow your code to specify if the shape range of a row or column of cells should skip the first cell. For example, if the first cell in a column is part of a heading row, you may want to skip formatting the cell like the others in a column.
Sub SetHeadingRowText(tbl As Table) tbl.Cell(1, 1).Shape.TextFrame _ .TextRange.Text = "Region" tbl.Cell(1, 2).Shape.TextFrame _ .TextRange.Text = "Projected" tbl.Cell(1, 3).Shape.TextFrame _ .TextRange.Text = "Actual" End Sub Sub SetFirstColumnText(tbl As Table) tbl.Cell(2, 1).Shape.TextFrame _ .TextRange.Text = "Northwest" tbl.Cell(3, 1).Shape.TextFrame _ .TextRange.Text = "Northeast" tbl.Cell(4, 1).Shape.TextFrame _ .TextRange.Text = "Southwest" tbl.Cell(5, 1).Shape.TextFrame _ .TextRange.Text = "Southeast" End Sub |