vba - 循环通过 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
解决方案
如果您将变量设置为范围并实际计算行数而不是硬编码行数,那么代码也会运行得更快。
您的问题表明 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)
推荐阅读
- android - Adb 通过 WiFi 连接到设备时检测到多个设备 React Native
- apache-kafka - kafka 主题中的 Wireshark/Tshark json 输出
- f# - 安装 F# 版本
- android - 带改造 2 的 Logut
- regex - 用于自定义占位符的 Groovy 正则表达式
- android - 如何从适配器外部获取我的 recyclerview 中显示的项目的位置?
- c - 指向另一个结构中的结构的双指针
- python - 基于属性迭代对象列表
- javascript - 在比较 classList.contains 的 if-else 语句时,如何在没有 setInterval 的情况下更新类?
- dns - 谷歌云 DNS 正确解析但超时