如果单元格值匹配,VBA 为单元格着色

标签 vba excel

我对 VBA 比较陌生,并且有一个脚本可以搜索数组“VC”并通过将其着色为红色来更改范围内的匹配单元格。

我的问题是我需要将条件从 -MyArr = Array("VC") 更改为搜索列 A 并在“B2:D20”范围内的同一行中找到任何相应的匹配项,然后将匹配项着色为红色下面的脚本可以。

根据下面的脚本,我不希望进行区分大小写的搜索,并使用 XLpart 来包含部分匹配项。请帮忙,谢谢

Sub Mark_cells_in_column()
    Dim FirstAddress As String
    Dim MyArr As Variant
    Dim Rng As Range
    Dim I As Long

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    MyArr = Array("VC")
    With Sheets("Sheet1").Range("A2:d20")
        For I = LBound(MyArr) To UBound(MyArr)
             Set Rng = .Find(What:=MyArr(I), _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
            If Not Rng Is Nothing Then
                FirstAddress = Rng.Address
                Do
                    Rng.Interior.ColorIndex = 3
                    Set Rng = .FindNext(Rng)
                Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
            End If
        Next I
    End With
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End Sub
<小时/>

示例数据:

Sample data

最佳答案

你可以试试这个

Public Sub Main()
    Dim cell As Range, cell2 As Range
    For Each cell In ThisWorkbook.Worksheets("Sheet1").Range("A2:A20")
        For Each cell2 In cell.Offset(, 1).Resize(, 3)
            If Instr(cell.Value, cell2.Value) > 0 Then cell2.Interior.ColorIndex = 3
        Next
    Next 
End Sub

或者

Public Sub Main()
    Dim cell As Range
    With ThisWorkbook.Worksheets("Sheet1")
        For Each cell In .Range("B:D").SpecialCells(xlCellTypeConstants)
            If Instr(.Cells(cell.Row,1).Value, cell.Value) > 0 Then cell.Interior.ColorIndex = 3
        Next
    End With 
End Sub

关于如果单元格值匹配,VBA 为单元格着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49640573/

相关文章:

Excel 仅在单元格宽度上加下划线(单元格的文本进入其他单元格)

excel - ByVal 是谎言吗?

android - 是否可以在 React Native 中使用 ExcelJS?

java - Java证书和vba证书有什么区别?

sql-server - ODBC 调用存储过程失败 - 通过查询

vba - 避免在此代码中使用 with activesheet

Excel VBA 选择最后一行和最后一列的范围

excel - 我可以仅使用 excel 的图表格式在月桶中显示每日数据吗?

vba - 如何使用 Excel 在打开的 Chrome 选项卡中打开新 URL,而无需打开新选项卡

excel - IronPython - 运行 Excel 宏