单词VBA选择一个句子

时间:2011-02-11 22:13:45

标签: ms-word word-vba

我想在Word文档中选择以粗体字开头的句子。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

怎么样:

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

我不太清楚“选择”是什么意思,你可以使用s.Select,但它只适用于一个句子。

编辑重新评论

非常粗略:

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

编辑重新评论#2

要比较的两个文件是相同的,所以也许:

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