Vba 根据相邻单元格中的字符串在Excel中高亮显示单元格中的字符串

Vba 根据相邻单元格中的字符串在Excel中高亮显示单元格中的字符串,vba,excel,string-matching,conditional-formatting,Vba,Excel,String Matching,Conditional Formatting,在这种情况下,我需要对单元格中的某些逗号分隔字符串应用一些条件格式,这取决于它们的[a-Z]前缀是否与相邻单元格中字符串的[a-Z]前缀不匹配。我正在使用的数据集示例如下: comma_separated_list string_to_match 1 BND170015,BND170027,BNL160006 BND12000512 2 BOL030017,ISS160014,ISS160015 ISS03000325 3 BIL160182,BIL160185,BI

在这种情况下,我需要对单元格中的某些逗号分隔字符串应用一些条件格式,这取决于它们的[a-Z]前缀是否与相邻单元格中字符串的[a-Z]前缀不匹配。我正在使用的数据集示例如下:

  comma_separated_list           string_to_match
1 BND170015,BND170027,BNL160006  BND12000512
2 BOL030017,ISS160014,ISS160015  ISS03000325
3 BIL160182,BIL160185,BIL160186  BIL13001102
4 SRD160238,SRD160239,SRD160240  SRD12000987
例如,在第一行中,条件格式应仅应用于“逗号分隔列表”列中的BNL160006。这是因为其字母前缀BNL与BND12000512的前缀(在“字符串匹配”列中)不匹配。在第2行中,条件格式应仅应用于BOL030017(因为它与ISS0300325不匹配)。等等

首先,我把一些东西放在一起,突出显示出现在右边的左边列中的任何前缀。然而,这并不是我所需要的;它只突出显示前缀(而不是整个字符串),我还希望它只突出显示不匹配的字符串

Sub ColourText()
    Dim xStr As String
    Dim xRg As Range
    Dim xCell As Range
    Dim xChar As String
    Dim I As Long
    Dim J As Long

    Set xRg = Range("B2:C10000")
    If xRg Is Nothing Then Exit Sub
    For I = 0 To xRg.Rows.Count - 1
        xStr = Left(xRg.Range("B1").Offset(I, 0).Value, 3)
        With xRg.Range("A1").Offset(I, 0)
            .Font.ColorIndex = 1
            For J = 1 To Len(.Text)
                If Mid(.Text, J, Len(xStr)) = xStr Then .Characters(J, Len(xStr)).Font.ColorIndex = 3
            Next
        End With
    Next I
End Sub

我还研究了如何通过公式实现这一点,但我看不到一种同时应用条件格式的方法。所以我现在有点困了。非常感谢您的帮助。

试试这样的

代码假定字符串放在A列中,要匹配的字符串放在B列中。根据需要修改它

Sub HighlightUnMatchedText()
Dim lr As Long, i As Long, Pos As Long
Dim Rng As Range, Cell As Range
Dim str() As String, critStr As String
Application.ScreenUpdating = False
lr = ActiveSheet.UsedRange.Rows.Count
Set Rng = Range("A2:A" & lr)
Rng.Font.ColorIndex = xlAutomatic
For Each Cell In Rng
    If Cell <> "" And Cell.Offset(0, 1) <> "" Then
        critStr = Left(Cell.Offset(0, 1), 3)
        str() = Split(Cell.Value, ",")
        For i = 0 To UBound(str)
            If Left(VBA.Trim(str(i)), 3) <> critStr Then
                Pos = InStr(Cell.Value, str(i))
                Cell.Characters(Pos, Len(str(i))).Font.Color = vbRed
            End If
        Next i
    End If
Next Cell
Application.ScreenUpdating = True
End Sub
Sub-HighlightUnMatchedText()
暗lr长,i长,Pos长
变暗Rng作为范围,单元格作为范围
Dim str()作为字符串,critStr作为字符串
Application.ScreenUpdating=False
lr=ActiveSheet.UsedRange.Rows.Count
设置Rng=范围(“A2:A”和lr)
Rng.Font.ColorIndex=xlAutomatic
对于Rng中的每个单元
如果单元格“”和单元格偏移量(0,1)”,则
critStr=Left(单元格偏移量(0,1,3)
str()=拆分(Cell.Value,“,”)
对于i=0到UBound(str)
如果左(VBA.Trim(str(i)),则3)critStr
Pos=仪表(单元值,str(i))
Cell.Characters(Pos,Len(str(i)).Font.Color=vbRed
如果结束
接下来我
如果结束
下一个细胞
Application.ScreenUpdating=True
端接头

前缀是否始终为3个字符?谢谢@sktneer。工作很愉快。