从子字符串中突出显示字符串

问题描述 投票:0回答:1

在 Excel 中,如何根据 B 列中的子字符串突出显示 A 列中字符串的部分内容? B 列中的子字符串可以是任意顺序,不一定遵循 A 列中的字符串的顺序

例如:

enter image description here

excel vba excel-2010
1个回答
0
投票

这将循环遍历单元格并比较两个字符串,将 B 中的所有逗号分隔列表拆分为一个数组,并将元素与 A 进行比较。

    Dim i As Long
    Dim lr As Long
    
    Dim wordarr As Variant
    Dim element As Variant
    Dim target As Long
    
    With Sheets(1)
        lr = .Cells(.Rows.Count, 1).End(xlUp).Row
        
        For i = 2 To lr
            If InStr(1, .Cells(i, 2).Value, ",") Then
                wordarr = Split(.Cells(i, 2).Value, ",")
                For Each element In wordarr
                    target = InStr(1, .Cells(i, 1).Value, element)
                    If target > 0 Then
                        .Cells(i, 1).Characters(target, Len(element)).Font.Color = RGB(255, 0, 0)
                    End If
                Next
            Else
                target = InStr(1, .Cells(i, 1).Value, .Cells(i, 2).Value)
                If target > 0 Then
                    .Cells(i, 1).Characters(target, Len(.Cells(i, 2).Value)).Font.Color = RGB(255, 0, 0)
                End If
            End If
        Next i
    End With
© www.soinside.com 2019 - 2024. All rights reserved.