我试图将sheet1上的名称与sheet2匹配,但是下面的代码仍在运行。我想要做的就是匹配(通过着色蓝色)如果sheet1上的名称至少包含sheet2上的部分名称。比如说;
sheet1:John Livingtone
表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
答案 0 :(得分: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)