tebdilikiyafet
tebdilikiyafet

Reputation: 405

Word VBA to choose a sentence

I want to choose sentences in a Word document which start with a bold character.

How can I do it?

Upvotes: 2

Views: 3600

Answers (1)

Fionnuala
Fionnuala

Reputation: 91376

How about:

Dim s As Range
For Each s In ActiveDocument.Sentences
    If s.Characters(1).Bold = True Then
        Debug.Print s
    End If
Next

I do not quite see what you mean by 'choose', you can use s.Select, but it will only work for one sentence.

EDIT re comments

Very roughly:

Dim s As Range
Dim doc1 As Document
Dim doc2 As Document

Set doc1 = Word.Documents("Doc1.doc")
Set doc2 = Word.Documents("Doc2.doc")

For Each s In doc1.Sentences
    If s.Characters(1).Bold = True Then
        Debug.Print s
        doc2.Select
            Selection.Find.ClearFormatting
            With Selection.Find
                ''.Text cannot be set to more than 256 characters
                .Text = s
                .Replacement.Text = ""
                .Forward = True
                .Wrap = wdFindContinue
                .Format = False
                .MatchCase = False
                .MatchWholeWord = False
                .MatchWildcards = False
                .MatchSoundsLike = False
                .MatchAllWordForms = False
            End With
            a = Selection.Find.Execute
            If a = True Then
                Selection.Characters(1).Font.Bold = True
                ''Or for the whole sentence
                Selection.Font.Bold = True
            End If
        doc1.Select
    End If
Next

EDIT re Comments #2

The two documents to be compared are identical, so perhaps:

Dim doc1 As Document
Dim doc2 As Document
Dim i As Integer

Set doc1 = Word.Documents("Doc1.doc")
Set doc2 = Word.Documents("Doc2.doc")

If doc1.Sentences.Count <> doc2.Sentences.Count Then
    MsgBox "These two documents do not match."
    Exit Sub
End If

For i = 1 To doc1.Sentences.Count
    If doc1.Sentences(i).Characters(1).Bold = True Then
        ''Debug.Print doc1.Sentences(i)
        If doc1.Sentences(i).Text = doc2.Sentences(i).Text Then
            doc2.Sentences(i).Bold = True
        Else
            MsgBox "Sentences do not match."
        End If
    End If
Next

Upvotes: 2

Related Questions