将颜色应用于范围中的特定单词

时间:2015-02-25 09:39:16

标签: excel vba excel-vba

我想将颜色应用于范围内的特定单词。例如,在下面的范围内,我想为单词添加颜色" Henry" (请注意一些细胞有一个以上的亨利"。我想为所有"亨利"添加颜色。

         A
1  Henry is Henry
2  Lean and REyhan came
3  Fendo Henry came 
4  dce
5  Henry and Henry uu Henry 

我的代码不仅将颜色应用于亨利,还将颜色应用于每个单元格的前五个字符。我不知道为什么。

Sub search()

  Set m_wsSheet1 = Sheets(1).Range("A1:A5")

  searchWord = "Henry"

  For Each celld In m_wsSheet1
    kkk = 1
    Do
      kkk = InStr(kkk, celld, searchWord )
      mmm = kkk
      celld.Characters(kkk, Len(searchWord)).Font.Color = RGB(221, 21, 221)
      kkk = kkk + Len(searchWord )
    Loop While mmm > 0
  Next

End Sub

提前谢谢

1 个答案:

答案 0 :(得分:2)

我使用你的变量名完成了一个版本。你在那里一半。只是不需要aaa或mmm变量,你的第二个工作表名称不正确,循环的退出条件不起作用。

将来确保缩进正确并声明变量。还尝试提出更好的变量名称。

Sub search()

'add in declarations
Dim m_wsSheet1 As Range
Dim celld As Range
Dim kkk As Integer
Dim searchWord As String
Dim blnEndSearch As Boolean


Set m_wsSheet1 = Sheets(1).Range("A1:A5")

searchWord = "Henry"

For Each celld In m_wsSheet1 'changed to same range as above

    kkk = 1 'starting search position

    Do
        'finds starting position of search word
        kkk = InStr(kkk, celld.Value, searchWord) 'changed aaa to searchWord

        'if we've found a match
        If kkk <> 0 Then
            'colours found word
            celld.Characters(kkk, Len(searchWord)).Font.Color = RGB(221, 21, 221)

            'start at end of last position
            kkk = kkk + Len(searchWord)
        End If

    Loop While kkk <> 0

Next

End Sub