[英]EXCEL VBA: make first cell with partial text match activecell with macro run, then next cell down the list with subsequent macro runs activecell
[英]Partial cell(or string) match in excel macro
我是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
我按照约翰·科尔曼的建议将声明从“字符串”更改为“范围”后,删除线部分已经解决,并且不再显示“编译错误”。
我通过将Name1和Name2都更改为Sally进行了测试,然后将以下条件用于删除线,它可以正常工作。 我认为是使条件无法使用的“ *”。
If ShiftName Like CashName Then
CashName.Font.Strikethrough = True
如何通过相应地更改条件来进行部分匹配?
第二编辑:
我的错! 我意识到我的Name1是大写的。
除了@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
并非绝对必要在范围变量上使用.Value
( Like
没有,则使用Like
的比较将按预期进行工作),但许多人认为,当使用范围变量而不是依赖于变量时,它是一种很好的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子句中做了什么。 如果没有-只是删除东西完全和有End If
后立即Exit Do
使用Like
运算符:
If Name1 Like "*" & Name2 Then
您可以将Like
用于特定的模式匹配,但也可以使用通配符*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.