如何在Excel中突出显示所选文本

时间:2012-07-26 15:28:53

标签: excel vba text highlight

我想编写一个VBA函数来突出显示excel单元格中的特定文本。这可能吗?我一直在谷歌搜索,但目前还不清楚。

澄清一下,我想在特定列中搜索文本值(实际上是值列表)并以黄色突出显示匹配的文本。

注意:这就是我最终要做的事情:

  Sub Colors()


    Dim searchString As String
    Dim targetString As String
    Dim startPos As Integer

    searchString = "abc"
    targetString = Cells(2, 1).Value
    startPos = InStr(targetString, searchString)

    If startPos > 0 Then

        Cells(2, 1).Characters(startPos, Len(searchString)).Font.Color = vbRed

    End If


 End Sub

6 个答案:

答案 0 :(得分:13)

这是基本原则,我假设自定义此代码不是您要求的(因为没有提供有关此内容的详细信息):

 Sub Colors()

 With Range("A1")
    .Value = "Test"
    .Characters(2, 2).Font.Color = vbGreen
 End With

 End Sub

小描述虽然它说得很好:第一个“2”指的是需要着色的第一个字符,第二个“2”指的是长度。

答案 1 :(得分:5)

这仅适用于未来读者试图突出显示单元格内的特定字符串模式

(这就是我解释这个问题的方式) 您可以在此示例中设置F1中要搜索的字符串

Sub test4String2color()
Dim strTest As String
Dim strLen As Integer
 strTest = Range("F1")
 strLen = Len(strTest)
For Each cell In Range("A1:D100")
 If InStr(cell, strTest) > 0 Then
  cell.Characters(InStr(cell, strTest), strLen).Font.Color = vbRed
 End If
Next
End Sub

答案 2 :(得分:2)

这个答案专门针对@ t.ztrk,他在Col1中有城市,在第2列搜索这些城市。他在这里发布了他的问题: is it possible to find and change color of the text in excel

我从另一个解决方案中借用了此代码(抱歉,如果它不是原始代码):https://stackoverflow.com/a/11676031/8716187

Sub test4String2color()
Dim strTest As String
Dim strLen As Integer
 strTest = Range("F1")
 strLen = Len(strTest)
For Each cell In Range("A1:D100")
 If InStr(cell, strTest) > 0 Then
  cell.Characters(InStr(cell, strTest), strLen).Font.Color = vbRed
 End If
Next
End Sub

我知道这可能并不优雅,但我在几分钟内就把它打了出来以满足用户的需求。如果上面提供的解决方案(1)更灵活或(2)更高效,请提前抱歉。对于我的C ++嵌套循环习惯也很抱歉。

@ t.ztrk你可以录制一个宏并停止它(删除那里的任何东西)或插入一个按钮控件并将代码粘贴在那里。不确定你的VB熟悉程度。只需确保在运行宏之前选择要处理的工作表上的单元格(它应该在任何工作表上运行,并且可以在任何工作簿上工作)。

Sub Macro1()
'Searches all text in Column 2 on a Sheet for the string located in Column 1
'If found it highlights that text
Dim ThisWB As Workbook
Dim ThisWS As Worksheet
Dim i As Integer
Dim y As Integer

Dim Col1 As Double
Dim Col2 As Double

Dim Col1_rowSTART As Double
Dim Col1_rowEND As Double

Dim Col2_rowSTART As Double
Dim Col2_rowEND As Double

Dim strTest As String
Dim strLen As Integer

'Set up parameter that we know
Set ThisWB = ActiveWorkbook
Set ThisWS = ActiveSheet
Col1 = 1 'city column
Col2 = 2 'text search column
'Define Starting Row for each column
Col1_rowSTART = 1
Col2_rowSTART = 1
'Define ending row for each column
Col1_rowEND = ThisWS.Cells(ThisWS.Rows.Count, Col1).End(xlUp).Row
Col2_rowEND = ThisWS.Cells(ThisWS.Rows.Count, Col2).End(xlUp).Row

'Could be fancy and see which column is shorter ....
'Won't do that here

For i = Col1_rowSTART To Col1_rowEND
    'make a string out of each cell value in Col1
    strTest = CStr(ThisWS.Cells(i, Col1))
    strLen = Len(strTest)
    'Roll thorugh all of Column 2 in search of the target string
    For y = Col2_rowSTART To Col2_rowEND
        'Check if Col1 string is in Col2 String
        If InStr(CStr(ThisWS.Cells(y, Col2)), strTest) > 0 Then
            ThisWS.Cells(y, Col2).Characters(InStr(ThisWS.Cells(y, Col2), strTest), strLen).Font.Color = vbRed
        End If
    Next y
Next i

MsgBox ("City Search Complete!")

End Sub

这是您的测试截图。 enter image description here

干杯 - 继续学习和应用。 -WWC

答案 3 :(得分:1)

在单元格中突出显示文本的一个问题是字符串可能出现多次,因此代码应该检查是否还有其他内容。这是我对这个问题的解决方案:

Sub Colors()


    Dim searchTerms As Variant


    searchTerms = Array("searchterm1", "searchterm2",  "lastsearchterm")


    Dim searchString As String
    Dim targetString As String
    Dim offSet As Integer
    Dim colToSearch As Integer
    Dim arrayPos, rowNum As Integer

    colToSearch = 3


    For arrayPos = LBound(searchTerms) To UBound(searchTerms)
        For rowNum = 2 To 31124

            searchString = Trim(searchTerms(arrayPos))

            offSet = 1

            Dim x As Integer

            targetString = Cells(rowNum, colToSearch).Value

            x = HilightString(offSet, searchString, rowNum, colToSearc)

        Next rowNum
    Next arrayPos

 End Sub

Function HilightString(offSet As Integer, searchString As String, rowNum As Integer, ingredCol As Integer) As Integer

            Dim x As Integer
            Dim newOffset As Integer
            Dim targetString As String


            ' offet starts at 1

            targetString = Mid(Cells(rowNum, ingredCol), offSet)

            foundPos = InStr(LCase(targetString), searchString)

            If foundPos > 0 Then

                ' the found position will cause a highlight where it was found in the cell starting at the offset - 1
                Cells(rowNum, ingredCol).Characters(offSet + foundPos - 1, Len(searchString)).Font.Color = vbRed

                ' increment the offset to found position + 1 + the length of the search string
                newOffset = offSet + foundPos + Len(searchString)

                x = HilightString(newOffset, searchString, rowNum, ingredCol)
            Else
                ' if it's not found, come back out of the recursive call stack
                Exit Function
            End If
End Function

答案 4 :(得分:1)

@Jack BeNimble 感谢您的代码,在10分钟内成功使用它来突出显示单元格中的所有数字。我重新整理了一下,先搜索一行中的所有搜索字词,然后是单元格,并允许多列。我发现一个错误,你的高亮文本不喜欢重复55,444,只突出显示序列中的奇数重复。在突出显示功能中修改了一行

newOffset = offSet + foundPos + Len(searchString) - 1 //added the - 1.

这是我修改过的代码。

Sub NumberColors()

Dim searchTerms As Variant


searchTerms = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".")


Dim searchString As String
Dim targetString As String
Dim offSet As Integer
Dim colsToSearch As Variant
Dim arrayPos, colIndex, colNum As Integer
Dim rowNum As Integer

colsToSearch = Array(4, 44, 45)


For colIndex = LBound(colsToSearch) To UBound(colsToSearch)
    colNum = colsToSearch(colIndex)
    For rowNum = 5 To 3000
        For arrayPos = LBound(searchTerms) To UBound(searchTerms)
            searchString = Trim(searchTerms(arrayPos))

            offSet = 1

            Dim x As Integer

            targetString = Cells(rowNum, colNum).Value

            x = HilightString(offSet, searchString, rowNum, colNum)
        Next arrayPos
    Next rowNum
Next colIndex

End Sub

函数HilightString(offSet As Integer,searchString As String,rowNum As Integer,ingredCol As Integer)As Integer

        Dim x As Integer
        Dim newOffset As Integer
        Dim targetString As String


        ' offet starts at 1

        targetString = Mid(Cells(rowNum, ingredCol), offSet)

        foundPos = InStr(LCase(targetString), searchString)

        If foundPos > 0 Then

            ' the found position will cause a highlight where it was found in the cell starting at the offset - 1
            Cells(rowNum, ingredCol).Characters(offSet + foundPos - 1, Len(searchString)).Font.Color = vbBlue

            ' increment the offset to found position + 1 + the length of the search string
            newOffset = offSet + foundPos + Len(searchString) - 1

            x = HilightString(newOffset, searchString, rowNum, ingredCol)
        Else
            ' if it's not found, come back out of the recursive call stack
            Exit Function
        End If

结束功能

感谢Jack BeNimbleand datatoo

答案 5 :(得分:-1)

您不需要VBA来执行此操作。您可以使用条件格式。

假设您在E列中有一组值。您想在单元格B1中输入一个值,并突出显示E列中与该值匹配的单元格。

突出显示E列中的单元格并应用以下条件格式:

highlight matching cells

更改颜色以适应。这将对列E中的单元格应用相对条件格式。例如:选择E3并查看条件格式,它应如下所示:

relative reference

您可以看到公式如何调整自己。

编辑:如果您想将B1中的值与E列中值的子字符串相匹配,请使用此条件格式设置公式:=FIND($B$1,E1)>0

现在在单元格B1中键入不同的值。如果键入的值与E列中的某个值匹配,则这些单元格(在E列中)将更改颜色。将单元格B1更改为E列中不存在的值,格式化将消失。