How change the style of a shape-text in vba? - vba

I changed the size of text with the following line of code
shp.CellsSRC(visSectionCharacter, 0, visCharacterSize).FormulaU = " 3pt"
I'd like to change the style (to Bold) and color of the shape text with the same pattern of code ?
I didn't find the exact "formula", would you know how I could do that ?
Thank you very much in advance
Edit : I found this line for the color :
shp.CellsSRC(visSectionCharacter, 0, visCharacterColor).FormulaU = "THEMEGUARD(RGB(255,0,0))"

I'm not sure why there is no enumeration for setting the Style. In any case, it's Column 2 in the shape properties. So use
shp.CellsSRC(visSectionCharacter, 0, 2).FormulaU = 17
to set your text to Bold.
How do I know this you ask? Based on the Microsoft reference on Understanding the Shape Sheet, there is a helpful snippet of code to use.
First, select the shape in your drawing that you want to see information about the properties. Then open up the Shape Properties window in the Visio editor (not in the VBE) -- you can get there by viewing the Developer ribbon, then click on the Show ShapeSheet icon
In the shape properties window, scroll down until you see the Characters section. You MUST select one of the cells in the properties window. The example here has selected the Style column.
Once you have done this, then run the following code snippet below and you'll get the information you need in the Immediate Window of the VBE.
Public Sub DebugPrintCellProperties()
' Abort if ShapeSheet not selected in the Visio UI
If Not Visio.ActiveWindow.Type = Visio.VisWinTypes.visSheet Then
Exit Sub
End If
Dim cel As Visio.Cell
Set cel = Visio.ActiveWindow.SelectedCell
'Print out some of the cell properties
Debug.Print "Section", cel.Section
Debug.Print "Row", cel.Row
Debug.Print "Column", cel.Column
Debug.Print "Name", cel.Name
Debug.Print "FormulaU", cel.FormulaU
Debug.Print "ResultIU", cel.ResultIU
Debug.Print "ResultStr("""")", cel.ResultStr("")
Debug.Print "Dependents", UBound(cel.Dependents)
' cel.Precedents may cause an error
On Error Resume Next
Debug.Print "Precedents", UBound(cel.Precedents)
Debug.Print "--------------------------------------"
End Sub
This will tell you the Section, Row, and Column to use when you call CellsSRC. What I did was to figure out the property, then I manually set the text to BOLD and viewed the results of DebugPrintCellProperties again to see that the FormulaU = 17 for bold.

Related

Unhighlighting text (and preserve all other font settings)

Thanks to 2 posts (here and here), I know how to highlight text of a textbox in PowerPoint with VBA code.
However, the problem of unhighlighting text remains unsolved. I tried to set properties of a non-highlighted textbox to TextRange2.Font (e.g. .TextFrame2.TextRange.Font.Highlight.SchemeColor = -2) but receive errors when trying so (The typed value is out of range).
Can someone help to solve this issue, please?
Additionally, when changing the highlight color
(e.g. TextRange2.Font.Highlight.RGB = RGB(255, 255, 175)) the formatting of my textbox changes, so the font is changing its color from my preset white to black and the font size gets smaller. Is there any way to preserve the original settings for the textbox? Is this happening due to the access of .TextRange2 and not .TextRange?
Thanks for your help!
In PowerPoint 2019/365 it is possible to remove highlight by using built-in Mso "TextHighlightColorPickerLicensed".
This code sample illustrates how to unhighlight text in selected shapes. It finds Runs containing highlighting, selects them and removes highlight by programmatically invoking Command Bar "Highlight" button.
Preconditions: PowerPoint 2019 or 365. Presentation must be opened with window.
Option Explicit
Sub UnhighlightTextInSelectedShape()
Dim sh As Shape
For Each sh In ActiveWindow.Selection.ShapeRange
UnhighlightTextInShape sh
Next
End Sub
Sub UnhighlightTextInShape(sh As Shape)
On Error GoTo Finish
Dim highlightIsRemoved As Boolean
Dim tf As TextFrame2
Set tf = sh.TextFrame2
Do
Dim r As TextRange2
highlightIsRemoved = True
For Each r In tf.TextRange.Runs
If r.Font.Highlight.Type <> msoColorTypeMixed Then
' Indicate that text contains highlighting
highlightIsRemoved = False
' The text to un-highlight must be selected
r.Select
If Application.CommandBars.GetEnabledMso("TextHighlightColorPickerLicensed") Then
' This Mso toggles highlighting on selected text.
' That is why selection must contain highlight of the same type
Application.CommandBars.ExecuteMso ("TextHighlightColorPickerLicensed")
' Unhighlighting May invalidate number of runs, so exit this loop
Exit For
Else
Exit Do
End If
End If
Next
Loop Until highlightIsRemoved
Finish:
If Not highlightIsRemoved Then
MsgBox "Unhighlighting is not supported"
End If
End Sub
Sometimes Application.CommandBars.ExecuteMso() method gives access to features not available via PowerPoint API.
The MsoId is displayed in tooltip text in PowerPoint options window:

Creating shapes in similar fashion as with autoshape dropdown

I would like to make a macro in Powerpoint that enables me to create shapes in a similar fashion as when you select the autoshapes in the autoshape overview (i.e. once you call the macro you have a possibility to click to set the coordinates and subsequently you drag and click to set the width&height). Also, I would like to give it pre-set cosmetic characteristics (e.g. certain inner margins, fill color, border style and transparancy), which will be defined in the vba code.
I am aware of .addshapes(), however, this requires coordinates and height/width as input. Moreover, I have not find any posts / documents on vba to create shapes without defined coordinates and height/width.
Anyone some ideas on how to tackle this challenge?
Many thanks in advance!
Sofar
Building on what John Korchok suggested, here's code that retrieves the just-drawn shape so that your code can resume and manipulate it...
Sub testAppComBars()
Dim SHP As Shape
Application.CommandBars.ExecuteMso ("ShapeFreeform")
Stop
Set SHP = Selection.ShapeRange(1)
With SHP.Fill
.ForeColor.RGB = RGB(192, 0, 0)
.Transparency = 0.75
End With
End Sub
I would hope there's a more elegant solution than using Stop to pause code execution while the user picks the shape's location (or in this case, draws a freeform polyline/polygon), but that's all I could come up with off the top of my head.
I was fascinated by this problem and think this might help you.
Consider that when you draw a new autoshape, you have changed the window selection, and created a new selection ShapeRange with exactly 1 item (the new shape).
So by setting a WindowSelectionChange event, you're able to apply any formatting you wish at the time of creation.
First create a class module called cPptEvents with the following:
Public WithEvents PPTEvent As Application
Private Sub PPTEvent_WindowSelectionChange(ByVal sel As Selection)
On Error GoTo Errhandler
Debug.Print "IN_PPTEvent_WindowSelectionChange"
Dim oShp As Shape
If (ActiveWindow.ViewType = ppViewNormal) Then
With sel
If .Type = ppSelectionShapes Then
If .ShapeRange.Count = 1 Then
Set oShp = .ShapeRange(1)
If oShp.Type = msoAutoShape Then
If oShp.AutoShapeType = msoShapeOval Then
If oShp.Tags("new_oval") = "" Then
oShp.Fill.ForeColor.RGB = RGB(255, 0, 0)
oShp.Tags.Add "new_oval", "true"
End If
End If
End If
End If
End If
End With
End If
Exit Sub
Errhandler:
Debug.Print "Error: " & Err.Description
End Sub
This checks the selection every time it changes. If there's an oval selected, it looks for the "new_oval" tag, which will not exist for a newly created shape. In that case, it applies a red fill, although of course once you get to this point you can call an entirely different sub, pass along the shape, and do whatever you want formatting-wise to it.
By adding that "new_oval" tag, you ensure that the formatting will not be applied to an oval that hasn't been newly created. This allows the user to make manual changes to the formatting as needed -- otherwise you're just resetting the formatting every time the user selects an oval.
Note that for the _WindowSelectionChange event to be running in the background, you have to call this at some point:
Public MyEventClassModule As New cPptEvents
'
Public Sub StartMeUp()
Set MyEventClassModule.PPTEvent = Application
End Sub
You can include that one line from StartMeUp above in whatever Ribbon_Onload sub is triggered by your addin, if you're making a new addin ribbon.
With this solution, you don't even have to give the end user a special button or set of tools to create the shapes that are being formatted. It happens invisibly whenever the user draws a new shape from the native PPT tools.
This will put your cursor in drawing mode to draw an oval. After running, you may have to click on the slide once, then the cursor will change shape and you can draw an oval:
Sub DrawOval()
Application.CommandBars.ExecuteMso ("ShapeOval")
End Sub
Other commands to substitute for ShapeOval:
ShapeRectangle
ShapeElbowConnectorArrow
ShapeStraightConnectorArrow
Get the full list in Excel spreadsheets from Microsoft Office 2016 Help Files: Office Fluent User Interface Control Identifiers
Look for the powerpointcontrols.xlsx file and search the first column with "shape"
There are 173 shapes in the menu, so you have a lot of macros to write.

VBA Picture Shadow Macro

I have a bunch of images that I would like to apply a specific picture style to - the 4th one that is shown in Word 2010:
I have a macro that will loop through all images, but need to know the possibilities for the shadow.type .
What would be really helpful is a reference to the commands that would be used for each type of picture style, with a visual example.
I don't have VBA, so can't examine the elements of the picture. I have tried various msoShadowxx, but that didn't work.
Is there a good reference with visual examples, or a reference with the settings for each picture style? Or the settings to use for the 4th picture style (shown in the screenshot here)?
Here is the macro code that I use to loop through all the pictures.
Sub BorderMacroshadow()
Dim oInlineShp As InlineShape
For Each oInlineShp In ActiveDocument.InlineShapes
With oInlineShp
.Line.Weight = 1
.Line.ForeColor.RGB = vbBlack
.Shadow.Type = msoShadow14
End With
Next
End Sub
Added
A closer look at the reference for msoShadow shows that it is referring to Picture Effects, Shadows 'dialog', not the 'Picture Styles', which I assumes uses some elements of msoShadow in addition to other elements.
So, I am looking for the elements that are needed to duplicate the 4th 'Picture Style' (see the screenshot). Haven't found those yet.
The msoShadowType enumeration is a group of pre-sets. These aren't necessarily used in the gallery on the Ribbon.
In order to ascertain the settings of any Shadows formatting use the various properties available for Shape.Shadow, such as Transparency, Size, Blur. Inthe UI, these can be seen in Picture Effects, Shadow, Shadow Options of the Picture Style group on the Ribbon.
To determine/set them programmatically, see the following code sample. Note that Angle is not one property, but a combintation of OffsetX and OffsetY.
Sub ShadowProperties()
Dim shp As Word.Shape
Dim shw As Word.ShadowFormat
Set shp = Selection.ShapeRange(1)
Set shw = shp.Shadow
With shw
Debug.Print "Blur: " & .Blur, _
"size: " & .Size, _
"Transparency: " & .Transparency, _
"Offset x: " & .OffsetX, _
"Offset y: " & .OffsetY
End With
End Sub

How to change an existing Tabstop in PowerPoint by VBA?

I have a VBA Code to resize objects in PowerPoint including Font size, margins and everything else. But I haven’t found a solution to update/change an existing TapStop. There is a the Ruler Object with different levels und a default value. I double checked also the TextRange Object with Characters.
Are there any ideas to update the TabStop size?
Here is an example of a TextBox, i would like to resize:
TextBox Example
Shape.textframe.ruler.tabstops.count is always 0, if I "take" just the shape by For-Each-Loop. If I select it manual, it's also 0 at the sub menu TabStops of Paragraph menu.
If I click inside the shape (blinking cursor) and open the TabStops menu again, I see one TabStopPosition.
How can I access this information by VBA?
I tried it already by Line.Selection and nothing works.
Thanks!
Moe
PowerPoint used to allow only one set of paragraph settings per textframe (ie, per shape). That changed in PPT2007; now each paragraph can have its own tab and other settings. Have a go with this:
Sub ShowMeTabs()
Dim X As Long
Dim lTabCount As Long
With ActiveWindow.Selection.ShapeRange(1).TextFrame2.TextRange
For X = 1 To .Paragraphs.Count
Debug.Print X
With .Paragraphs(X).ParagraphFormat
For lTabCount = 1 To .TabStops.Count
Debug.Print .TabStops(lTabCount).Position
Next ' Tab
Debug.Print "Level:" & .IndentLevel & " Position:" & .LeftIndent 'etc
End With
Next ' paragraph x
End With
End Sub

Understanding format of tables in PowerPoint (VBA 2010) (resize text to cell)

Following issue:
I declare tbl as Table in VBA. I want to show some tables in PowerPoint.
If the text of the cells are too long, the cells get big and they go beyond the slide limits. I want to avoid that. I just want to resize the text, that means, I just want that the text gets smaller, in order to fit within the cell. That means, cell-table size should not be changed!
How would you do that? I've tried:
ppPres.Slides(NumSlide).Shapes(NumShape).Table.Columns(col).Cells(1).Shape.TextFrame2.AutoSize = msoAutoSizeTextToFitShape
without success. Could you please tell me what's wrong and how would you proceed?
The error message is as follows:
Run-Time error '2147024809 (80070057)'
The specified value is out of range.
This is one of the oddities of the PowerPoint OM. The Shape object has all of the properties listed by IntelliSense, including the AutoSize property, yet when referenced within a table, some properties are not available. AutoSize is one of them. For example, if you place your cursor within a cell and open the the Format Shape pane in PowerPoint, you can see that the 3 AutoSize radio buttons are greyed out as well as the Wrap text in shape checkbox:
In the above example, which was created by adding the table via the PowerPoint UI rather than programmatically, I then copied the text from cell 2,1 to 1,2 with this code and the cell didn't change width but does change height, potentially forcing the table off of the bottom of a slide:
ActiveWindow.Selection.ShapeRange(1).Table.Cell(1,2).Shape.TextFrame.TextRange.Text=_
ActiveWindow.Selection.ShapeRange(1).Table.Cell(2,1).Shape.TextFrame.TextRange.Text
If it's this that you're trying to control, you'll need to do it manually in code via examining the table cell and/or table height after inserting your text and reducing the font size iteratively and rechecking each reduction level to see if the table is still out of the slide area.
This code does that for you:
Option Explicit
' =======================================================================
' PowerPoint Subroutine to iteratively reduce the font size of text
' in a table until the table does not flow off the bottom of the slide.
' Written By : Jamie Garroch of YOUpresent Ltd. http://youpresent.co.uk/
' Date : 05DEC2016
' Inputs : Table object e.g. ActiveWindow.Selection.ShapeRange(1).Table
' Outputs : None
' Dependencies : None
' =======================================================================
Sub FitTextToTable(oTable As Table)
Dim lRow As Long, lCol As Long
Dim sFontSize As Single
Const MinFontSize = 8
With oTable
Do While .Parent.Top + .Parent.Height > ActivePresentation.PageSetup.SlideHeight
For lRow = 1 To .Rows.Count
For lCol = 1 To .Columns.Count
With .Cell(lRow, lCol).Shape
sFontSize = .TextFrame.TextRange.Font.Size
If sFontSize > MinFontSize Then
.TextFrame.TextRange.Font.Size = sFontSize - 1
Else
MsgBox "Table font size limit of " & sFontSize & " reached", vbCritical + vbOKOnly, "Minimum Font Size"
Exit Sub
End If
End With
' Resize the table (effectively like dragging the bottom edge and allowing PowerPoint to set the table size to the text.
.Parent.Height = 0
Next
Next
Loop
End With
End Sub