【问题标题】:Code to highlight a specific word in a specific column in Excel在 Excel 的特定列中突出显示特定单词的代码
【发布时间】:2017-09-10 23:35:59
【问题描述】:

我正在搜索一个在特定列中搜索特定关键字并将其突出显示为黄色的 excel 代码;并且能够为多个列执行此操作,每个列都有自己不同的关键字。

示例:

  • 在 A 列中搜索关键字“河流”
  • 在 B 列中搜索关键字“海洋”
  • 在 C 列中搜索关键字“sea”

每次,唯一关键字仅在特定列中突出显示,即使它也可能出现在其他列中。

该代码将包含 100 列,从“A 列”到“CV 列”,并允许为每一列插入唯一的关键字。

这可能吗?

在论坛中搜索时,我发现了在 excel 中突出显示特定单词的代码,但没有将搜索范围缩小到一列并从其他列中排除关键字。

这段代码,找到一个单词并把它涂成红色,有一个类似的核心思想:

Sub colorText()

    Dim cl As Range
    Dim startPos As Integer
    Dim totalLen As Integer
    Dim searchText As String
    Dim endPos As Integer
    Dim testPos As Integer

 ' specify text to search.
 searchText = "river"

' loop trough all cells in selection/range
 For Each cl In Selection

  totalLen = Len(searchText)
  startPos = InStr(cl, searchText)
  testPos = 0

  Do While startPos > testPos
     With cl.Characters(startPos, totalLen).Font
      .FontStyle = "Bold"
      .ColorIndex = 3
    End With

    endPos = startPos + totalLen
    testPos = testPos + endPos
     startPos = InStr(testPos, cl, searchText, vbTextCompare)
  Loop

Next cl

End Sub

只有我需要黄色高光,而不是红色。我需要它用于 excel 2016,此代码适用于 excel 2010。

谢谢。

【问题讨论】:

  • 使用宏记录器生成可以根据需要修改的代码。可以使用 VBA 颜色常量,例如:ActiveCell.Interior.Color = vbYellow

标签: excel vba search cell highlight


【解决方案1】:

编辑:您可以突出显示单元格或更改单元格中特定文本的字体颜色。 Excel 没有突出显示单元格中特定文本背景的选项。

由于您只想看到搜索到的字符串被着色,因此我使用了 Font.ColorIndex 属性和红色而不是黄色,以便于查看。

我还声明了一个数组,以便您可以随意输入预定义的 100 个唯一关键字。

让我知道它是否适合你:

Sub Search_by_Column()
Dim rng As Range
Dim i As Long
Dim oldrngrow As Long
Dim myValue As String
Dim arr() As Variant

arr = Array("river", "ocean", "sea") '..... keep going till 100 keywords

For i = 1 To UBound(arr) + 1
   myValue = arr(i - 1)
   If myValue = vbNullString Then
      End
   End If
   Set rng = Cells.Find(What:=myValue, After:=Cells(1, i), LookIn:=xlFormulas, LookAt _
      :=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _
      False, SearchFormat:=False)
   If rng Is Nothing Then
      GoTo Skip
   End If

   oldrngrow = rng.Row
   Do While rng.Column = i
      rng.Characters(InStr(rng, myValue), Len(myValue)).Font.ColorIndex = 3
      Set rng = Cells.FindNext(After:=rng)
      If oldrngrow = rng.Row Then
        Exit Do
      End If
   Loop
Skip:
Next i
End Sub

【讨论】:

  • 非常感谢您回答我的问题。我刚刚试过你的代码。黄色可以用作突出显示而不是文本颜色吗?有没有办法自动应用突出显示,而无需每列手动输入单词?
  • 您要突出显示关键字的背景还是整个单元格?您是否计划为 100 列搜索 100 个唯一关键字?这 100 个关键字是事先为每列确定的吗?
  • 是的,只是关键字本身的背景,而不是单元格整个单元格。我只是希望能够在阅读文本时更好地看到关键字。总的来说,我拥有的每个文档都有 100 列,并且每列都有自己独特的关键字,我希望能够突出显示黄色,以便更快地扫描文档。这可以做到吗? (谢谢。对于延迟回复感到抱歉。我出城探亲,今天刚回来)。
猜你喜欢
  • 2017-10-29
  • 2019-06-24
  • 2014-03-08
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
  • 2021-06-28
  • 2020-10-11
  • 1970-01-01
相关资源
最近更新 更多