PDA

View Full Version : formatting lost



alex54
05-15-2021, 12:19 AM
I have a Word document with the following content:
1 2 3
Number 2 is bold.
I want to insert a text (Hello!) immediately after the number 1.
The VBA program below performs the insertion:

Sub forum()
Set X = Selection.Range
Set Y = X.Paragraphs(1)
Set Z = Y.Range
Z.Select
Selection.CopyFormat
X.Text = Left(Z, 1) & "Hello!" & Mid(Z, 2)
Z.Select
Selection.PasteFormat
End Sub

The result is:
1Hello! 2 3

Formatting is lost (no bold).
How can I keep the same effect but keep the formatting?

gmayor
05-20-2021, 08:25 PM
X.Text = removes the bold. What you want is something like

Sub forum()Dim x As Range
Set x = Selection.Paragraphs(1).Range
Do Until x.Characters(1).Font.Bold = True
x.Start = x.Start + 1
Loop
x.Collapse 1
x.Text = "Hello! "
x.Font.Bold = True
Set x = Nothing
End Sub

alex54
05-27-2021, 12:33 AM
Thank you.