首页 > 解决方案 > 循环通过 Instr Excel VBA

问题描述

我正在尝试将 sheet1 上的名称与 sheet2 匹配,但下面的代码不起作用。如果 sheet1 上的名称至少包含 sheet2 上的部分名称,我要做的就是匹配(通过着色为蓝色)。比如说;

表 1:约翰·利文顿

sheet2:约翰·利文

Sub inst()

    Dim nameone As Variant
    Dim cel As Variant
    Dim nametwo As Variant
    Dim cem As Variant

    nameone = Sheets("Sheet1").Range("L1:L1600")
    nametwo = Sheets("sheet2").Range("M1:M1600")

    For Each cem In nameone

        For Each cel In nametwo

            If InStr(cem.Value, "cel.Value") > 0 Then
                cem.Value = RGB(0, 0, 255)
            End If

        Next cel

    Next cem

标签: vbaexcel

解决方案


如果您将变量设置为范围并实际计算行数而不是硬编码行数,那么代码也会运行得更快。

您的问题表明 sheet2 具有部分字符串,但您的代码显示相反。我根据您提供的代码运行了循环。

Sub inst()

    Dim nameone As Range
    Dim cel As Range
    Dim nametwo As Range
    Dim cem As Range
    Dim sh1 As Worksheet, sh2 As Worksheet
    Dim L1 As Long, L2 As Long

    Set sh1 = Sheets("Sheet1")
    Set sh2 = Sheets("Sheet2")

    With sh1
        L1 = .Cells(.Rows.Count, "L").End(xlUp).Row
        Set nameone = .Range("L1:L" & L1)
    End With

    With sh2
        L2 = .Cells(.Rows.Count, "M").End(xlUp).Row
        Set nametwo = .Range("M1:M" & L2)
    End With



    For Each cem In nameone.Cells
        For Each cel In nametwo.Cells

            If InStr(cem.Value, cel.Value) <> 0 Then
                cem.Font.Color = RGB(0, 0, 255)
            End If

        Next cel

    Next cem
End Sub

如果您希望单元格为蓝色而不是字体,请更改内部颜色

 cem.Interior.Color = RGB(0, 0, 255)

推荐阅读