在Excel宏中部分匹配单元格(或字符串)

6

我是VBA的新手,我想在两个工作表之间进行部分字符串(或单元格)匹配。

例如,Name1的示例为“IT执行官Sally Lim”

Name2的示例为“Sally Lim”

Name1 = Sheets("Work").Cells(RowName1, ColName1)
Name2 = Sheets("Roster").Cells(RowName2, ColName2)

'This condition doesn't work
If Name1 = "*" & Name2 & "*" Then
    'The "Name2" comes out with a compile error: Invalid Qualifier
    Name2.Font.Strikethrough
    Exit Do
Else
    End If

然而,它并没有起作用。运行代码时,要么什么都不会发生,要么会弹出错误。请帮忙解决。

编辑后的代码:

If ShiftName Like "*" & CashName & "*" Then
    CashName.Font.Strikethrough = True

在 John Coleman 的建议下,我将声明从“string”更改为“range”,因此已经解决了划去部分并且不再显示“编译错误”。

我测试了将 Name1 和 Name2 都更改为 Sally,然后使用以下条件进行划掉,它可以正常工作。我相信是“*”使得该条件无法工作。

If ShiftName Like CashName Then
    CashName.Font.Strikethrough = True

如何通过相应地更改条件来进行部分匹配?
第二次编辑:
对不起!我意识到我的Name1是大写字母。

那段代码怎么能运行?变量名不能以数字开头。 - SierraOscar
那么,我该怎么改变它才能使它工作?请给我指点。谢谢。 - stupidgal
2个回答

5
除了 @MacroMan 的答案提到使用Like之外,您还需要正确使用Strikethrough。它是一个需要设置为True的布尔属性:
If Name1 Like "*" & Name2 Then
    Name2.Font.Strikethrough = True
    Exit Do
Else
    End If

关于编辑:

根据您扩展的问题,您可以像这样做:

Dim Name1 As Range, Name2 As Range 'If you don't have this already declared

'then ... in the loop:

Set Name1 = Sheets("Work").Cells(RowName1, ColName1)
Set Name2 = Sheets("Roster").Cells(RowName2, ColName2)

If Name1.Value Like "*" & Name2.Value & "*" Then
    Name2.Font.Strikethrough = True
    Exit Do
Else
    End If

在处理Range变量时,严格来说不需要使用.Value(使用Like进行比较时,即使没有.Value也可以正常工作),但许多人认为,在使用范围变量时明确指定是良好的VBA编码风格,而不是依赖于范围对象的默认属性。

你也可以完全不使用变量Name1和Name2:

If Sheets("Work").Cells(RowName1, ColName1).Value Like "*" & Sheets("Roster").Cells(RowName2, ColName2).Value & "*" Then
   Sheets("Roster").Cells(RowName2, ColName2).Font.Strikethrough = True
    Exit Do
Else
    End If

最后一点说明:紧随Else之后的End If有点毫无意义。假设您的实际代码在else子句中执行了某些操作。如果没有 - 只需完全删除else并在Exit Do之后立即使用End If

感谢您提供帮助。但是,当我运行这段代码时,Name2 出现了“编译错误:无效限定符”的提示。 - stupidgal
@stupidgal,“IT高管Sally Lim” Like“”&“Sally Lim”&“”肯定会评估为“True”。也许在代码中加入Debug.Print Name1.Value&“ ”&Name2Value,并告诉我们你看到了什么。 - John Coleman
@JohnColeman 我错了,我意识到我的Name1是大写的,这导致了无响应。 - stupidgal
@stupidgal 我有时会使用像 UCase(Trim(s)) Like "*" & UCase(Trim(t)) & "*" 这样的东西来进行比较,使其不区分大小写和周围的空格。 - John Coleman
@stupidgal 实验一下。如果你弄不明白,就发个新问题。避免在评论中提出相关但不同的问题。 - John Coleman
显示剩余4条评论

3

使用Like运算符:

If Name1 Like "*" & Name2 Then

你可以使用Like进行特定模式匹配,但它也允许通配符*

上面的代码没有起作用。当我运行它时,条件没有得到响应。 - stupidgal
那么 Name1 显然不以 Name2 结尾。这些答案基于您问题中的代码 - 我们看不到您看到的值。 - SierraOscar
也许我会再次进行检查。 - stupidgal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接