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

时间:2018-04-03 23:36:53

标签: excel vba excel-vba

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

我的问题是我需要将标准从-MyArr = Array(“VC”)改为搜索A列,并在“B2:D20”范围内的同一行中找到任何相应的匹配,然后将匹配的颜色设置为红色为下面的脚本呢。

根据以下脚本,我不想进行区分大小写的搜索,并且使用XLpart来包含部分匹配。请帮助,谢谢

{{1}}

示例数据:

Sample data

2 个答案:

答案 0 :(得分:4)

你可以试试这个

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

答案 1 :(得分:2)

这将遍历A列中的所有单元格,将每个单元格值(逗号分隔)拆分为单独的项目,并通过列B到D

搜索同一行中的每个项目(不区分大小写)
Option Explicit

Public Sub MarkCellsInColumns()
    Dim arr As Variant, r As Long, c As Long, i As Long, f As Range, vals As Variant

    arr = Sheet1.UsedRange

    With Sheet1.UsedRange
        For r = 1 To UBound(arr)
            If Not IsError(arr(r, 1)) Then
                If Len(arr(r, 1)) > 0 Then

                    vals = Split(arr(r, 1), ",")        'check each value in one cell
                    For i = 0 To UBound(vals)
                        For c = 2 To UBound(arr, 2)     'check all columns on same row
                            If LCase(Trim$(vals(i))) = LCase(Trim$(arr(r, c))) Then
                                If f Is Nothing Then
                                    Set f = .Cells(r, c)
                                Else
                                    Set f = Union(f, .Cells(r, c))  'union of found cells
                                End If
                                f.Select
                            End If
                        Next c
                    Next i

                End If
            End If
        Next r
        If Not f Is Nothing Then f.Interior.Color = vbRed   'color all in one operation
    End With
End Sub

结果

Result