简体   繁体   English

遍历Instr Excel VBA

[英]Looping Through Instr Excel VBA

I'm trying to match names on sheet1 with sheet2 but the code below ain't working. 我正在尝试将sheet1上的名称与sheet2匹配,但是下面的代码不起作用。 All I want to do is to match(by coloring blue) if the name on sheet1 contains at least part of the name on sheet2. 我要做的就是如果sheet1上的名称至少包含sheet2上名称的一部分,则匹配(用蓝色涂)。 Say for example; 举例来说;

sheet1: John Livingtone 工作表1:John Livingtone

sheet2 : John Living 工作表2:约翰·利文(John Living)

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

If you set your variables to ranges and actually count the rows instead of hard coding the number of rows, the code would work faster as well. 如果将变量设置为范围并实际计算行数,而不是对行数进行硬编码,则代码也将更快地工作。

Your question shows that sheet2 has the partial string, but your code shows the opposite. 您的问题表明sheet2具有部分字符串,但是您的代码却显示了相反的字符串。 I ran the loop according to the code you provided. 我根据您提供的代码运行了循环。

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

If you wanted the cell to be blue and not the font, then change the interior color 如果您希望单元格为蓝色而不是字体,请更改内部颜色

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM