How to change a text in a word document by using excel vba

86 views Asked by At

I have created a program in Excel VBA, this program copy from Word document content and paste it to the mail body. But I have tried to change the direction of one text in the document and used .ParagraphFormat.Alignment but it didn't work.

I tried this code

Sub sendMail()


    Dim ol As Outlook.Application
    Dim olm As Outlook.MailItem
    Dim wd As Word.Application
    Dim doc As Word.Document
    Dim Cell As Range



    For r = 23 To Sheet1.Cells(Rows.Count, 21).End(xlUp).Row

        With wd.Selection.Find
        
            .Text = "<<Duration>>"
            .Replacement.Text = Sheet1.Cells(r, 32).Value
            .Execute Replace:=wdReplaceAll
        
        End With
        
        
        With wd.Selection.Find
        
            .Text = "<<objectivs>>"
            .ParagraphFormat.Alignment = wdAlignParagraphLeft   'this code suppose to change the direction but it didn't work
            .Replacement.Text = Sheet1.Cells(r, 33).Value
            .Execute Replace:=wdReplaceAll
            
        End With


    Next


End Sub
3

There are 3 answers

1
kcp On

Try

.Replacement.ParagraphFormat.Alignment = wdAlignParagraphLeft
2
macropod On

Your code is looking for a paragraph with the required alignment, not setting it. The use of Selection is also very inefficient. Try:

For r = 23 To Sheet1.Cells(Rows.Count, 21).End(xlUp).Row
  With wd.ActiveDocument.Range.Find
    .Text = "<<Duration>>"
    .Replacement.ClearFormatting
    .Replacement.Text = Sheet1.Cells(r, 32).Value
    .Execute Replace:=wdReplaceAll
    .Text = "<<objectivs>>"
    .Replacement.ParagraphFormat.Alignment = wdAlignParagraphLeft
    .Replacement.Text = Sheet1.Cells(r, 33).Value
    .Execute Replace:=wdReplaceAll
  End With
Next

Note that, unless you want all except the first <<Duration>> paragraph's format changed, you need to ensure it is cleared for each iteration.

0
Abu Ali On

I found it, it is supposed to be like this:

.Replacement.ParagraphFormat.ReadingOrder = wdReadingOrderLtr