MS Word 2016 - 使用VBA查找具体内容并更改其样式

时间:2018-03-27 15:07:23

标签: vba ms-word word-vba

我想在MS Word 2016中找到特定的单词并将它们应用于它们。

受旧帖子的启发:MS Word VBA - Finding a word and changing its style

我创建了一个带有'Linked'Style类型的样式NewStyle,可以用作字符样式。我运行了前面提到的帖子的宏:

Sub FnR4()
Dim rng As Range
Dim mykeywords
mykeywords = Array("word1", "word2", "word3")
Dim nkey As Integer

For nkey = LBound(mykeywords) To UBound(mykeywords)
For Each rng In ActiveDocument.Words
    Selection.Collapse
    rng.Select
        If mykeywords(nkey) = LCase(Trim(rng.Text)) Then
            Selection.Style = ActiveDocument.Styles("NewStyle")
        End If

Next rng
Next nkey

End Sub

当我运行宏时,没有任何反应......不知道问题是什么!

其次,我不想使用难以编辑的数组。我想指向一个txt文件,每行包含一个单词。

1 个答案:

答案 0 :(得分:1)

根据以下内容尝试:

Sub BulkStyleUpdate()
Application.ScreenUpdating = False
Dim FRDoc As Document, FRList, i As Long
Set FRDoc = Documents.Open(FileName:="Drive:\FilePath\FindList.doc", ReadOnly:=True, AddToRecentFiles:=False, Visible:=False)
FRList = FRDoc.Range.Text
FRDoc.Close False
Set FRDoc = Nothing
With ActiveDocument.Range.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .MatchWholeWord = True
  .MatchCase = True
  For i = 0 To UBound(Split(FRList, vbCr)) - 1
    .Text = Split(FRList, vbCr)(i)
    .Replacement.Text = "^&"
    .Replacement.Style = "NewStyle"
    .Execute Replace:=wdReplaceAll
  Next
End With
Application.ScreenUpdating = True
End Sub

当然,您需要为单词列表提供正确的文件详细信息。文件格式可以是Word支持的任何有效格式。