我正在尝试在 Microsoft Word 中创建一个 VBA 宏,它将:
首先选择一段文本作为“颜色键”。所选内容中的每一行都有唯一的颜色和文本字符串。
存储选择中每行的字体颜色和文本。
在文档的其余部分搜索字体颜色与“颜色键”选择中的任意颜色匹配的段落。
将颜色键中匹配的文本添加到具有相同字体颜色的任何段落的前面。
如果选择了三行并且运行了宏,预期的输出应该是这样的。
代码,我尝试过
Sub ApplyColorKeyPrefixes()
Dim doc As Document
Dim selectedRange As Range
Dim colorKeyColors As Collection
Dim colorKeyPrefixes As Collection
Dim para As Paragraph
Dim line As Range
Dim colorCode As Long
Dim prefixText As String
Dim i As Long
' Initialize document and collections for color key
Set doc = ActiveDocument
Set colorKeyColors = New Collection
Set colorKeyPrefixes = New Collection
Set selectedRange = Selection.Range
For i = 1 To selectedRange.Paragraphs.Count
Set line = selectedRange.Paragraphs(i).Range
line.End = line.End - 1 ' Exclude paragraph mark
' Store the color and corresponding text
colorCode = line.Font.Color
prefixText = Trim(line.Text)
On Error Resume Next
colorKeyColors.Add colorCode, CStr(colorCode)
colorKeyPrefixes.Add prefixText, CStr(colorCode)
On Error GoTo 0
Next i
'oop through all paragraphs in the document (after selection) to find matches
For Each para In doc.Paragraphs
' Skip paragraphs in the initial selection
If para.Range.Start >= selectedRange.End Then
Set line = para.Range.Words(1) ' use first text of selection to determine color
colorCode = line.Font.Color
' Check if color match in parag
On Error Resume Next
prefixText = colorKeyPrefixes(CStr(colorCode))
On Error GoTo 0
If prefixText <> "" Then
para.Range.InsertBefore prefixText & ": "
' Retain color for the og text and the prefix text
para.Range.Words(1).Font.Color = colorCode
para.Range.Font.Color = colorCode
End If
End If
Next para
Set colorKeyColors = Nothing
Set colorKeyPrefixes = Nothing
End Sub
问题 代码当前将前缀应用于所有段落,而不仅仅是字体颜色匹配的段落。我怀疑我在 colorKeyPrefixes 中检查字体颜色匹配的方式可能存在问题,但我不确定问题出在哪里。
我如何修改宏,以便它仅将前缀文本附加到与所选“颜色键”中的某一行具有相同字体颜色的段落?
附加说明 所选内容中的每一行都保证只有一种颜色。颜色键最多可包含 12 种不同的颜色。我使用每个段落的第一个单词来检查颜色(假设该颜色适用于整个段落)。