Apply Font Formatting to PowerPoint Text Programmatically - vba

I am trying to use VBA to insert some text into a PowerPoint TextRange, I use something like this:
ActiveWindow.Selection.SlideRange.Shapes("rec1").TextFrame.TextRange.Text = "Hi"
However, I can't figure out how to apply bold, italic and underline programmatically (I don't see a .RichText property or something similar).
What I have is some simple HTML text with bold, italic and underlined text I would like to convert over.
How to do this?

This is easily accomplished by using the TextRange's Characters, Words, Sentences, Runs and Paragraphs objects and then it's Font object to set Bold, Underline and Italic (amongst other properties). For example:
Sub setTextDetails()
Dim tr As TextRange
Set tr = ActiveWindow.Selection.SlideRange.Shapes(1).TextFrame.TextRange
With tr
.Text = "Hi There Buddy!"
.Words(1).Font.Bold = msoTrue
.Runs(1).Font.Italic = msoTrue
.Paragraphs(1).Font.Underline = msoTrue
End With
End Sub

Try looking at MSDN's documentation on the TextRange object. It contains samples of how to access the Font properties of the TextRange object.
EDIT: You can access things like Bold and Italics programmatically in this manner:
TextRange.Font.Bold = msoTrue
EDIT EDIT: There are several methods by which you can select only certain text in a text range. See the following:
Characters Method
Lines Method
Paragraphs Method
Words Method
According to the sames from this link, you can select a portion of the text using one of these methods and set the font programmatically. For example:
Application.ActiveDocument.Pages(1).Shapes(2) _
.TextFrame.TextRange.Words(Start:=2, Length:=3) _
.Font.Bold = True
That example was taken from the Words Method link.

In addition to the above answer, you should try to name the objects you'll be changing, since selecting them in the middle of a presentation could make PowerPoint act oddly. Create a new TextRange object and set it like this.
dim mytextrange As TextRange
Set mytextrange = ActiveDocument.Pages(1).Shapes(2).TextFrame.TextRange
mytextrange.Words...

Here is how you can do it to change the font of a specific text:
Sub changeFont()
Dim oPresentation As Presentation
Dim oSlide As Slide
Dim oShape As Shape
Dim stringSearched As String
stringSearched = "something"
'all opened presentations
For Each oPresentation In Presentations
'all slide in them
For Each oSlide In oPresentation.Slides
'all shapes (anything)
For Each oShape In oSlide.Shapes
'only those that contain text
If oShape.HasTextFrame Then
If InStr(oShape.TextFrame.TextRange.Text, stringSearched) > 0 Then
'here you need to define where the text ends and start
oShape.TextFrame.TextRange.Characters(InStr(oShape.TextFrame.TextRange.Text, stringSearched), Len(stringSearched)).Font.Underline = msoTrue
oShape.TextFrame.TextRange.Characters(InStr(oShape.TextFrame.TextRange.Text, stringSearched), Len(stringSearched)).Font.Italic = msoFalse
End If
End If
Next
Next
Next
End Sub

Related

Changing colour of text segments in a powerpoint presentation

I have a Powerpoint-Slide with pasted, formatted source code in the form of text shapes. Sadly the contrast of some part of that text is bad on a projector, so I would like to change every colour occurence for a specific font with a different colour. In this specific example I want to replace the orange colour:
Iterating over all shapes and accessing the whole text of a shape is not a problem, but I can't find any property that allows me to enumerate over the styled text segments:
Sub ChangeSourceColours()
For Each pptSlide In Application.ActivePresentation.Slides
For Each pptShape In pptSlide.Shapes
If (pptShape.Type = 1) And (pptShape.TextFrame.TextRange.Font.Name = "Consolas") Then
' Iterate over styled segments and change them if the previous colour is orangey
MsgBox pptShape.TextFrame.TextRange
End If
Next
Next
End Sub
The TextRange2 property looked helpful at a first glance, but looking at the variables in the debugger I see nothing that looks like a series of formatted segments. I would expect to find something like <span> in HTML to check and possibly change the colour.
The textFrame2.textRange.Font is valid for the whole text. If you want to access the single characters and their individual formatting, you need to access textRange.Characters.
The following routine changes the text color for all characters that have a specific color to a new color:
Sub ChangeTextColor(sh As Shape, fromColor As Long, toColor As Long)
Dim i As Long
With sh.TextFrame2.TextRange
For i = 1 To .Characters.Length
If .Characters(i).Font.Fill.ForeColor.RGB = fromColor Then
.Characters(i).Font.Fill.ForeColor.RGB = toColor
End If
Next i
End With
End Sub
You call it from your code with
Dim pptSlide as Slide
For Each pptSlide In Application.ActivePresentation.Slides
Dim pptShape As Shape
For Each pptShape In pptSlide.Shapes
If (pptShape.Type = 1) And (pptShape.TextFrame.TextRange.Font.Name = "Consolas") Then
ChangeTextColor pptShape, RGB(255, 192, 0), vbRed
End If
Next
Next
You will have to adapt the RGB-Code to the orange you are using, or instead of using RGB, you can use ObjectThemeColor. To avoid a type mismatch, you need to declare the pptShape variable as Shape - you should declare all your variables and use Option Explicit anyhow.
Note that you can use the ChangeTextColor-routine also in Excel (and probably also in Word). Shapes are defined similar in Excel and Powerpoint. Advantage in Excel: You can use the macro recorder to get some insights how a Shape can be used in Office VBA.

Visio VBA: How to make all text in Org Chart Bold

I would like to simplify updating my orgcharts in Visio. So far I have a macro borrowed from here https://bvisual.net/2010/01/28/applying-selected-datagraphic-to-the-whole-document/ and written out below. I would like to adapt it to make some changes to the format of the text withing shapes e.g. to make the font bold and potentially to change it's colour. I'm finding it really difficult to find examples of this online so any help/suggestion would be greatly appreciated.
Public Sub ApplyDataGraphicToDocument()
Dim mstDG As Visio.Master
Dim shp As Visio.Shape
Dim pag As Visio.Page
Dim firstProp As String
If Visio.ActiveWindow.Selection.Count = 0 Then
MsgBox "Please select a shape which already has data graphics"
Exit Sub
Else
Set shp = Visio.ActiveWindow.Selection.PrimaryItem
If shp.DataGraphic Is Nothing Then
MsgBox "Please select a shape which already has data graphics"
Exit Sub
Else
'Get the shapes DataGraphic master
Set mstDG = shp.DataGraphic
'Get the name of the first Shape Data row
firstProp = "Prop." & _
shp.CellsSRC(Visio.visSectionProp, 0, 0).RowNameU
End If
End If
For Each pag In Visio.ActiveDocument.Pages
If pag.Type = visTypeForeground Then
For Each shp In pag.Shapes
'Check that the named Shape Data row exists
If shp.CellExistsU(firstProp, Visio.visExistsAnywhere) Then
'Set the DataGraphic
shp.DataGraphic = mstDG
End If
Next
End If
Next
End Sub
You can modify the default OrgChart shapes, although it is not officially supported. To change the default shapes (make their font bold), you'll need to edit the templates (masters) for those OrgChart shapes. In the same blog you can find more information on customizing the OrgChart diagrams, here: https://bvisual.net/2012/05/08/creating-a-custom-org-chart-template-with-extra-properties
The procedure is mostly the same, just instead of adding the properties, you make the text bold.

Changing Font Outline color inside a Table Cell with VBA using Application.CommandBar.ExecuteMSO

Win10x64 Office 365 PPT v 16.0.12325.202080 64-bits
I need to show a character with a yellow font color but a black outline, for readability purposes. This character goes inside a Powerpoint table Cell.
The following link has a method that I'm currently using that consists of creating a dummy shape, adding text to it, modify the shape's textframe2 textrange font line properties and then copying it and pasting it back to the table cell.
http://www.vbaexpress.com/forum/archive/index.php/t-43787.html
This was asked 8 years ago, but I'm currently seeing the same behaviour where we can't directly manipulate the textframe2 wordart format of text inside a cell. The program doesn't show an error but doesn't work.
I have given up on trying to modify the textrame2 textrange font line properties directly from VBA.
I have managed to get it to activate the font outline color using
Application.CommandBars.ExecuteMso ("TextOutlineColorPicker")
After it's activated I thought I could modify the textframe2 textrange font line properties, but it still doesn't work.
Is there an Application.CommandBars idMso for changing the font outline color and font outline line width inside a table cell?
Or another other than pasting the formatted text inside a table cell.
Edit:
Adding an image to illustrate what I mean by text color and text outline color and the menu used to show them in red circle:
Edit2
Added another snapshot to exemplify a character inside a cell with black outline and a character inside a cell without an outline
Thanks
Here's an example to access a Table on a given slide and change one cell's attributes. The example slide I'm using looks like this
The code itself creates a function that allows you to select a table from a particular slide, and a single cell within the table and highlight it.
Option Explicit
Sub test()
HighlightTableCell 1, 2, 3
End Sub
Sub HighlightTableCell(ByVal slideNumber As Long, _
ByVal thisRow As Long, _
ByVal thisCol As Long)
Dim theSlide As Slide
Set theSlide = ActivePresentation.Slides(slideNumber)
Dim shp As Shape
For Each shp In theSlide.Shapes
If shp.Type = msoTable Then
Dim theTable As Table
Set theTable = shp.Table
With theTable.Cell(thisRow, thisCol)
With .Shape.TextFrame2.TextRange.Characters.Font.Fill
.Visible = msoTrue
.ForeColor.RGB = RGB(255, 255, 0)
.Transparency = 0
.Solid
End With
With .Shape.TextFrame2.TextRange.Characters.Font.Line
.Visible = msoTrue
.ForeColor.ObjectThemeColor = msoThemeColorText1
.ForeColor.TintAndShade = 0
.ForeColor.Brightness = 0
.Transparency = 0
End With
End With
End If
Next shp
End Sub
This question should be answered by Microsoft Office developers.
Currently, to overcome this bug-some situation, I think, copying the formatted text outside the table and pasting it into a table cell is the only work-around for this trouble.
As you mentioned, according to John Wilson, one of the most brilliant PowerPoint MVPs(http://www.vbaexpress.com/forum/archive/index.php/t-43787.html), if we copy the text from a textbox or shape that is located outside of the table, the format of the text can be preserved even for the text in a table cell.
Option Explicit
Sub test()
Dim shp As Shape, tshp As Shape
Dim sld As Slide
Dim tbl As Table
Dim r%, c%
If ActiveWindow.Selection.Type = ppSelectionNone Then MsgBox "Select a table first.": Exit Sub
Set shp = ActiveWindow.Selection.ShapeRange(1)
Set sld = shp.Parent
'add a temporary textbox for copying the formatted text into a cell
Set tshp = sld.Shapes.AddTextbox(msoTextOrientationHorizontal, 0, 541, 960, 540)
tshp.Visible = False
Set tbl = shp.Table
For r = 1 To tbl.Rows.Count
For c = 1 To tbl.Columns.Count
'1) cell -> 'tshp'
tbl.Cell(r, c).Shape.TextFrame2.TextRange.Copy
tshp.TextFrame2.TextRange.Paste
'2) outline the text in 'tshp'
With tshp.TextFrame2.TextRange.Font.Line
.Visible = msoTrue
.Weight = 0.2
.ForeColor.RGB = RGB(255, 127, 127)
End With
'3) 'tshp' -> cell
tshp.TextFrame2.TextRange.Copy
tbl.Cell(r, c).Shape.TextFrame2.TextRange.Paste
'// the code below doesn't work
'With tbl.Cell(r, c).shape.TextFrame2.TextRange.Characters.Font.Line
'With tbl.Cell(r, c).shape.TextFrame2.TextRange.Font.Line
' .Visible = msoTrue
' .Weight = 0.5
' .ForeColor.RGB = RGB(255, 127, 127)
'End With
Next c
Next r
'remove the tempoarary textbox
tshp.Delete
End Sub
The above snippet creates a temporary textbox on left-top area of the slide and applies the outlined text format. Then, it copies the content of each cell to the temporary textbox and copy/paste the formatted text back to the cell. By using this method, we can apply the outlined text format to the text in a cell.

Setting same font type to whole presentation using VBA

I would like to set font type (calibri)of text( where ever there is an alphabet in presentation, it should be "calibri") in every slide by running the single macro using VBA. The problem is, it is unable to change the font present in 'chart', 'flow chart diagram' where it has boxes like rectangle, round cornered rectangles etc.How to manipulate that text as well? Please help!
As shown in the image the font of climate in rectangle is not changing.Different font type in rectangle
The solution to this problem is pretty tedious as there are so many different types of shapes and textranges to account for. I can't post my entire solution as I don't own the intellectual property, but this should get you on the right track:
Sub MakeFontsThemeFonts()
Dim oSld As Slide
Dim oShp As Shape
Dim oShp2 As Shape
Dim oTxtRange As TextRange
' Set majorFont and minorFont to Calibri
ActivePresentation.SlideMaster.Theme.ThemeFontScheme.majorFont.Item(1) = "Calibri"
ActivePresentation.SlideMaster.Theme.ThemeFontScheme.minorFont.Item(1) = "Calibri"
For Each oSld in ActivePresentation.Slides
For Each oShp in oSld.Shapes
If oShp.HasChart Then
' Call your chart handler
ElseIf oShp.HasTable Then
' Call your table handler
ElseIf oShp.HasSmartArt Then
' Call your SmartArt handler
ElseIf oShp.HasTextFrame Then
If oShp.HasText Then
Set oTxtRange = oShp.TextFrame.TextRange
Call RefontTextRange (oTxtRange)
End If
ElseIf oShp.Type = msoGroup Then
For Each oShp2 in oShp.GroupItems
If oShp2.Type = ... Then
' And so on, you wind up having to check for
' everything that's grouped all over again
End If
Next
End If
Next
Next
End Sub
Sub RefontTextRange (oTxtRange As TextRange)
With oTxtRange.Font
' Sets the textrange to the body font. If you want to make some stuff the heading font and some stuff the body font, you need to do more checking before sending here
.Name = "+mn-lt"
End With
End Sub
So that's the start of the solution, but this will get maddening for a few reasons. For tables, you'll have to parse the TextRange of every cell individually and pass those TextRanges on to your Refont sub. For charts, you may have to check for every imaginable chart element before setting your TextRange and refonting (my case was more complex than just setting the font to be the theme font, and I didn't have success trying to format the ChartArea all at once).
Are you having the issue with "floating" shapes inside of a chart? When you say "flow chart," is that an embedded Visio diagram or native SmartArt? There are many ways to skin this cat, but the solution will require you to identify every possible type of text container that can be accessed using VBA.
Here's one more tip that might help you get at those floating shapes within charts:
oShp.Chart.Shapes(1).TextFrame.TextRange.Font.Name = "+mn-lt"
But of course first you need to make sure you've got a chart, that it's got shapes in it, that those shapes have a textframe...
If you leverage the features already built in to PowerPoint, you won't need any code at all. The font theme is built to handle these situations. Format all text with font choices that include the (body) or (headings) tag in the name. Then when you switch the font theme from Arial to Calibri, all text, including charts and SmartArt, will be updated.
For a presentation that is already formatted with local formatting instead of using a font theme, unzipping the file to XML and using a good text editor's Find and Replace functions, you can quickly replace all instances of a font without programming.
Find 'typeface="Arial"'
Replace 'typeface="Calibri"'
Then rezip the files and restore the file ending.
It seems you only need to change the master slides (including notesmaster, slidemaster), instead of working on each slide. Here are my codes
Sub ChangeFont()
' https://stackoverflow.com/a/57212464/2292993
' affect SmartArt font
ActivePresentation.SlideMaster.Theme.ThemeFontScheme.majorFont.Item(1) = "Garamond"
ActivePresentation.SlideMaster.Theme.ThemeFontScheme.minorFont.Item(1) = "Garamond"
For i = 1 To Application.ActivePresentation.NotesMaster.Shapes.Count
With Application.ActivePresentation.NotesMaster.Shapes(i).TextFrame.TextRange.Font
.Name = "Garamond"
If Application.ActivePresentation.NotesMaster.Shapes(i).Name Like "Notes*" Then
.Bold = msoFalse
.Size = 16
End If
End With
Next i
' http://skp.mvps.org/2007/ppt003.htm
' Each design contained a slide master and possibly a title master. Several designs could be stored within a presentation.
' The slide master can contain several custom layouts which can be fully customized.
For Each oDesign In ActivePresentation.Designs
' slide master
Set sm = oDesign.SlideMaster
For j = 1 To sm.Shapes.Count
If sm.Shapes(j).HasTextFrame Then
With sm.Shapes(j).TextFrame.TextRange.Font
.Name = "Garamond"
End With
End If
Next j
' custom layouts
lngLayoutCount = oDesign.SlideMaster.CustomLayouts.Count
For I = 1 To lngLayoutCount
Set oCL = oDesign.SlideMaster.CustomLayouts(I)
For j = 1 To oCL.Shapes.Count
If oCL.Shapes(j).HasTextFrame Then
With oCL.Shapes(j).TextFrame.TextRange.Font
.Name = "Garamond"
End With
End If
Next j
Next I
Next
End Sub

VBA for Microsoft PowerPoint to recognize and hide text boxes in German language

I need to make two presentations with the same slides, backgrounds, and everything except for the text: one in German and one in English. Therefore I have two separate presentations which I must always simultaneously update, otherwise one language version will be outdated and I often forget what I changed.
I have made a custom show with all of the slides copied into one PowerPoint presentation and that works fairly well, but I still must change two of the same slides each time that I make an edit to one language.
Therefore, I'm trying to write a macro that will recognize all textboxes within the presentation with German text in them and hide them during the show, and vice versa. Then, each of the macros would be linked to a hyperlinked box on the title slide called 'English' or 'German' which, when clicked, would hide the textboxes in the other languages while also leaving all pictures and formatting the same. Ideally, the macro would hide all boxes in one language and make all the boxes in the other language visible again within the same step, so that the presentation is always usable and I don't have a user who opens a PPT with 'no text boxes' because they would all be hidden...
In order to achieve this I have two text boxes containing the text in both languages on the same slide, that's why I'd like to hide the textboxes.
I am able to get all text boxes hidden but not text boxes in a specific language (aka, all boxes regardless of their editing language will get hidden but not any specific ones).
PS - text boxes do not NEED to be referenced here... it could just refer to a shape. I was trying to avoid, that Pictures would be hidden and thought text boxes would be the best way to reference what I wanted.
Is there a better way?
I don't really know how to reference a language in VBA, I found this website by accident and thought someone might have a quick trick to help me out with this issue. The code I have which will blend out textboxes but not blend out specific language-boxes is as follows:
Sub GermanTextBoxFinder()
Dim SlideToCheck As Slide
Dim ShapeIndex As Integer
' Visit each slide
For Each SlideToCheck In ActivePresentation.Slides
' On each slide, count down through the shapes
For ShapeIndex = SlideToCheck.Shapes.Count To 1 Step -1
' If the shape IS a text box and DOES have German text
If SlideToCheck.Shapes(ShapeIndex).Type = msoTextBox And _
MsoLanguageID.msoLanguageIDGerman _
Then
' Toggle visibility of German Textboxes
SlideToCheck.Shapes(ShapeIndex).Visible = msoFalse
End If
Next
Next
End Sub
Why don't you name the shapes with German text something that identifies them? E.g. use the prefix "txtGER" for the texts in German and "txtENG" for the ones in English. Then you could use something like the following:
If SlideToCheck.Shapes(ShapeIndex).Type = msoTextBox And _
Left(SlideToCheck.Shapes(ShapeIndex).Name, 6) = "txtGER" Then
' Toggle visibility of German Textboxes
SlideToCheck.Shapes(ShapeIndex).Visible = msoFalse
Else
SlideToCheck.Shapes(ShapeIndex).Visible = msoTrue
End If
(Please see this q+a for information on how to rename the shapes).
This will hide text boxes/shapes with text that contain either English or French. You can modify HideFrench to hide German instead ... Intellisense will provide the correct constants.
Sub HideEnglish()
Dim oSl As Slide
Dim oSh As Shape
For Each oSl In ActivePresentation.Slides
For Each oSh In oSl.Shapes
If oSh.HasTextFrame Then
If oSh.TextFrame.HasText Then
If oSh.TextFrame.TextRange.LanguageID = msoLanguageIDEnglishUS Then
oSh.Visible = False
Else
oSh.Visible = True
End If
End If
End If
Next
Next
End Sub
Sub HideFrench()
Dim oSl As Slide
Dim oSh As Shape
For Each oSl In ActivePresentation.Slides
For Each oSh In oSl.Shapes
If oSh.HasTextFrame Then
If oSh.TextFrame.HasText Then
If oSh.TextFrame.TextRange.LanguageID = msoLanguageIDFrench Then
oSh.Visible = False
Else
oSh.Visible = True
End If
End If
End If
Next
Next
End Sub