部分单元格(或string)在Excelmacros中匹配
我是VBA的新手,我想在两张纸之间进行部分string(或单元格)匹配。
Name1的一个例子是“IT主pipeSally 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
但是,它不工作。 当我运行编码时,没有任何反应,或者popup一个错误。 请帮忙
编辑的编码:
If ShiftName Like "*" & CashName & "*" Then CashName.Font.Strikethrough = True
删除部分已经被解决了,并且在John Coleman提议将我的声明从“string”改为“range”之后,它不再显示“Compile Error”了。
我通过将Name1和Name2更改为两个Sally进行testing,然后使用以下条件进行删除,并且工作正常。 我相信这是“*”使条件变得不可行。
If ShiftName Like CashName Then CashName.Font.Strikethrough = True
如何通过相应地改变条件来完成部分匹配?
第二次编辑:
我的错! 我意识到我的名字1在CAPTIALS。
除了@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
在Rangevariables上使用.Value
并不是必须的(使用Like
的比较可以按照预期的方式进行,没有它),但是很多人认为使用范围variables时显式的VBA编码风格相对于依赖于范围对象的默认属性。
你也可以完全省去variablesName1
和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子句中做了一些事情。 如果没有 – 只需要删除其他的东西,并在Exit Do
之后立即结束
使用Like
运算符:
If Name1 Like "*" & Name2 Then
你可以使用Like
来进行特定的模式匹配,但是它也允许通配符*