简体   繁体   English

使用C#或VBA找出MS Word文档中突出显示的文本的背景色

[英]Find out background color of highlighted text in MS Word document using C# or VBA

Following finds the highlighted text in a Word document (even if the different text at different places is highlighted with different colors). 以下内容可在Word文档中找到突出显示的文本(即使不同位置的不同文本使用不同的颜色突出显示)。 How can we find out the background color of each highlighted text. 我们如何找出每个突出显示的文本的背景色。 I'm using C# but VBA will also be ok: 我正在使用C#,但VBA也可以:

With ActiveDocument.Range.Find
  .Highlight = True
  While .Execute
    Debug.Print .Parent.Text
  Wend
End With

The below statement would get you the color index of selected text in MS Word 下面的语句将为您提供MS Word中所选文本的颜色索引

Dim objSelection As Selection
Set objSelection = Application.Selection
Msgbox objSelection.FormattedText.HighlightColorIndex

The value returned is one of wdColorIndex enumeration. 返回的值是wdColorIndex枚举之一。 List of values in enumeration can be seen here https://msdn.microsoft.com/en-us/library/bb237561(v=office.12).aspx 枚举中的值列表可以在此处查看https://msdn.microsoft.com/zh-cn/library/bb237561(v=office.12).aspx

Update#1 更新#1

Below code is using ActiveDocument.Range.Find as requested 下面的代码按要求使用ActiveDocument.Range.Find

Dim objSelection As Selection
Dim temp As String

With ActiveDocument.Range.Find
  .Highlight = True
  While .Execute
    'Store the text for searching later
    temp = .Parent.Text

    'Select all the text
    ActiveDocument.Content.Select

    'Find and select the text
    With Selection.Find
        .Text = temp
    End With

    If Selection.Find.Execute Then
        Selection.Select
    End If

    'Now that we've selected it, get the HighlightedColorIndex
    Set objSelection = .Application.Selection
    MsgBox .Parent.Text & vbNewLine & "Index: " & objSelection.FormattedText.HighlightColorIndex
  Wend
End With

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM