上下文
我有一个Word文档,我想进行检查以确保它符合标准格式。该文档填充了1行项目符号点。我想解析每一行并检查与单词“测试”匹配的每个单词,以确保其为粗体。
问题
我能够解析每一行,并检查该行是否包含单词,但是不确定如何仅检查找到的所选内容是否为粗体。
当前代码
Sub checkWords()
Dim singleLine As Paragraph 'bullet point document so just went by each paragraph
Dim lineText As String
Dim pos As Integer
For Each singleLine In ActiveDocument.Paragraphs
pos = InStr(singleLine, "Testing")
If pos <> 0 Then
MsgBox ("Testing InStr")
End If
'PSEUDOCODE
'If singleLine.Range.Font.Bold <> True Then
' Do This
'End If
Next singleLine
End Sub
答案 0 :(得分:2)
尝试以下代码:
Sub checkWords()
Dim singleLine As Paragraph
Dim rng As Range
Dim pos As Integer
For Each singleLine In ActiveDocument.Paragraphs
Set rng = singleLine.Range
pos = InStr(1, rng.Text, "Testing")
If pos <> 0 Then
rng.Start = pos
rng.End = pos + Len("Testing")
If rng.Font.Bold Then
MsgBox "This is bold"
End If
End If
Next
End Sub
答案 1 :(得分:2)
您的原始问题是您想“解析每一行并检查与“测试”一词匹配的每个词,以确保其为粗体”。这并不意味着要进行任何决策。允许用户选择涉及更多:
Sub Demo()
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Testing"
.Replacement.Text = ""
.Forward = True
.Format = False
.Wrap = wdFindStop
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
.Select
Select Case MsgBox("Bold this instance?", vbYesNoCancel)
Case vbCancel: Exit Sub
Case vbNo: .Font.Bold = False
Case vbYes: .Font.Bold = True
End Select
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
End Sub
以上内容使您可以取消粗体显示的内容。要仅处理非粗体内容,可以使用:
Sub Demo()
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Testing"
.Replacement.Text = ""
.Forward = True
.Format = True
.Font.Bold = False
.Wrap = wdFindStop
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
.Select
Select Case MsgBox("Bold this instance?", vbYesNoCancel)
Case vbCancel: Exit Sub
Case vbYes: .Font.Bold = True
End Select
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
End Sub
答案 2 :(得分:0)
您正在做的事情比需要做的要困难得多。一个简单的“查找/替换”就可以完成这项工作,就像“查找/替换”宏一样:
Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Font.Bold = True
.Text = "Testing"
.Replacement.Text = "^&"
.Forward = True
.Format = True
.Wrap = wdFindContinue
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
End With
Application.ScreenUpdating = True
End Sub