Microsoft Word VBA 宏 - 一段查找替换样式
Microsoft Word VBA Macro - One Paragraph Find-Replace Styles
我正在使用 VBA 宏在 Microsoft Word 中执行样式搜索。
我的目标是对文档中找到的每种样式执行一次特定操作。
该宏在至少包含两个段落的文档上可以正常工作,但宏不会在其中只有一个段落的文档中正确提醒样式。这似乎很奇怪,当我输入一个新的段落标记时,样式被找到了,即使我没有向文档添加任何新文本或样式,只是一个额外的空白段落标记。有谁知道我的宏有什么问题以及如何解决这个问题?感谢您的观看。
Sub AlertAllStylesInDoc()
Dim Ind As Integer
Dim numberOfDocumentStyles As Integer
Dim styl As String
Dim StyleFound As Boolean
numberOfDocumentStyles = ActiveDocument.styles.count
For Ind = 1 To numberOfDocumentStyles
styl = ActiveDocument.styles(Ind).NameLocal
With ActiveDocument.Content.Find
.ClearFormatting
.text = ""
.Forward = True
.Format = True
.Style = styl
Do
StyleFound = .Execute
If StyleFound = True Then
' actual code does more than alert, but keeping it simple here'
MsgBox styl
GoTo NextStyle
Else
Exit Do
End If
Loop
End With
NextStyle:
Next
End Sub
我不明白为什么 ActiveDocument.Content
不起作用,但将其替换为 ActiveDocument.Range(0,0)
似乎可以解决问题(已在 Word 2016 中测试)。
With ActiveDocument.Range(0, 0).Find
我正在使用 VBA 宏在 Microsoft Word 中执行样式搜索。 我的目标是对文档中找到的每种样式执行一次特定操作。
该宏在至少包含两个段落的文档上可以正常工作,但宏不会在其中只有一个段落的文档中正确提醒样式。这似乎很奇怪,当我输入一个新的段落标记时,样式被找到了,即使我没有向文档添加任何新文本或样式,只是一个额外的空白段落标记。有谁知道我的宏有什么问题以及如何解决这个问题?感谢您的观看。
Sub AlertAllStylesInDoc()
Dim Ind As Integer
Dim numberOfDocumentStyles As Integer
Dim styl As String
Dim StyleFound As Boolean
numberOfDocumentStyles = ActiveDocument.styles.count
For Ind = 1 To numberOfDocumentStyles
styl = ActiveDocument.styles(Ind).NameLocal
With ActiveDocument.Content.Find
.ClearFormatting
.text = ""
.Forward = True
.Format = True
.Style = styl
Do
StyleFound = .Execute
If StyleFound = True Then
' actual code does more than alert, but keeping it simple here'
MsgBox styl
GoTo NextStyle
Else
Exit Do
End If
Loop
End With
NextStyle:
Next
End Sub
我不明白为什么 ActiveDocument.Content
不起作用,但将其替换为 ActiveDocument.Range(0,0)
似乎可以解决问题(已在 Word 2016 中测试)。
With ActiveDocument.Range(0, 0).Find