Question

I'm stumped about this thing - when recording a macro where I basically add some fields and go into Design Mode to be able to replace the dummy text of the placeholder. Now, I go out of Design Mode when recording the macro and everything seems to be working ok. But when playing the macro, it just stops after ActiveDocument.ToggleFormsDesign.

What could be causing this? Has anyone else experienced this?

Here's a snippet of a macro:

Selection.Range.ContentControls.Add (wdContentControlText)
ActiveDocument.ToggleFormsDesign
Selection.TypeText Text:="Date"
Selection.MoveLeft Unit:=wdCharacter, Count:=4, Extend:=wdExtend
Selection.Style = ActiveDocument.Styles("TextRed")
ActiveDocument.ToggleFormsDesign
Was it helpful?

Solution

The reason is because the Selection object becomes lost after ToggleDesignMode - meaning there is no longer a Selection object. In your recorded example, you reselected the place in which to type "Date" but Word doesn't know where to select.

The way to get around this is to use recorded macros as a starting point, but then further clean them up. Like this:

Sub InsertContentControl()
    Dim myDoc As Document
    Set myDoc = ActiveDocument
    Dim tr As Style
    Set tr = myDoc.Styles("TextRed"):
    Dim cc As ContentControl
    Dim sel As Range
    Set sel = Selection.Range
    Set cc = sel.ContentControls.Add(wdContentControlText)
    cc.SetPlaceholderText Text:="Date"
    cc.DefaultTextStyle = tr
End Sub

To do this with a new style, use the following:

Sub InsertContentControlwithNewStyle()
    Dim myDoc As Document
    Set myDoc = ActiveDocument
    Dim tr As Style
    Set tr = myDoc.Styles.Add("New TextRed")
    tr.BaseStyle = wdStyleNormal
    tr.Font.ColorIndex = wdRed
    Dim cc As ContentControl
    Dim sel As Range
    Set sel = Selection.Range
    Set cc = sel.ContentControls.Add(wdContentControlText)
    cc.SetPlaceholderText Text:="Date"
    cc.DefaultTextStyle = tr
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top