【问题标题】:Looping Through Instr Excel VBA循环通过 Instr Excel VBA
【发布时间】:2026-02-05 23:45:02
【问题描述】:

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

sheet1:约翰·利文顿

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

【问题讨论】:

  • "cel.Value" 删除 "" 即 cel.Value
  • 如果你在变量周围加上引号,它会被视为文字字符串,这可能不是你想要的。
  • FWIW 您也在使用 Range 对象,因此可以声明为这样而不是 Variants。
  • 也可以改变文字的颜色,使用cem.Font.Color = RGB(0, 0, 255)

标签: vba excel


【解决方案1】:

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

您的问题表明 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)

【讨论】: