Log in

View Full Version : Multiple text formats in selection; character format question



jc79
02-14-2013, 06:31 AM
I'm trying to create a macro that formats the selection with a strikethrough and bold, then inserts text before and after the selection with bold text. Below is the macro I've started:

Selection.Font.StrikeThrough = True
Selection.InsertBefore "<D>"
Selection.InsertAfter "<D>"
Selection.Font.bold = True

The output looks something like this, although I can't find a strikethrough font option in the post editor so have underlined it instead:

<D>text goes here<D>

This macro sometimes works :dunno

If my selection includes the space after the last word, it will format the way I want it to. But if I don't select the space after the last word, the second <D> retains the formatting of the original selection. The first <D> is never affected.

I think this has something to do with how Word retains character-level formatting but I can't seem to figure it out. Any assistance would be greatly appreciated.

macropod
02-14-2013, 10:33 PM
Try:
Sub Demo()
Dim StrTag As String
StrTag = "<D>"
With Selection
.InsertBefore StrTag
.InsertAfter StrTag
.End = .End - Len(StrTag)
.Start = .Start + Len(StrTag)
With .Font
.Bold = True
.StrikeThrough = True
End With
End With
End Sub

jc79
02-20-2013, 02:34 PM
Thanks Paul, that's great.

Where would I edit the code to format the <D>? Say the main text remains strikethrough but not bold, while the <D> is bolded both times?

macropod
02-20-2013, 03:01 PM
Where would I edit the code to format the <D>? Say the main text remains strikethrough but not bold, while the <D> is bolded both times?
In that case, you need to divide the operations into what you want to apply to the whole range and what you want to apply to the shorter portion of it. For example:
Sub Demo()
Dim StrTag As String
StrTag = "<D>"
With Selection
.InsertBefore StrTag
.InsertAfter StrTag
.Font.Bold = True
.End = .End - Len(StrTag)
.Start = .Start + Len(StrTag)
.Font.StrikeThrough = True
End With
End Sub