如何用VBA实现查找特定的字符串并将该单元格变色

2025-03-11 01:54:27
推荐回答(3个)
回答1:

代码及注释如下:
Private Sub CommandButton1_Click()
For i = 1 To 100'行数从1循环到100
For j = 1 To 100'列数从1到100循环
If InStr(UCase(Cells(i, j).Value), "ABC") Then'先将单元格转换为大写,再判断其中是否含有“ABC"字符串
ActiveSheet.Cells(i, j).Interior.Color = 65535 '如果含有,则将当前工作表的当前单元格填充底色
End If
Next
Next
End Sub

回答2:

在excel中按Alt+F8,
宏名: Macro1 创建
在打开的界面里输入如下代码,关闭。
'---------------------------------------------------------------------------
Sub Macro1()
Dim str1 As String
Dim color As Integer
str1 = "ABC" ' 要查找的内容
color = 3 '要更改的颜色 索引 ‘3’红色

With Application.ReplaceFormat.Font
.Superscript = False
.Subscript = False
.ColorIndex = color
End With
Cells.Replace What:=str1, Replacement:=str1, LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
ReplaceFormat:=True
End Sub
'---------------------------------------------------------------------------------------------------------------

回答3:

Private Sub CommandButton1_Click()

    For i = 1 To 100

        For j = 1 To 100

            If InStr(UCase(Cells(i, j).Value), "ABC") Then

                ActiveSheet.Cells(i, j).Interior.Color = 65535 '黄色

            End If

        Next

    Next

End Sub