stu*_*gal 5 excel vba excel-vba string-matching strikethrough
我是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
Run Code Online (Sandbox Code Playgroud)
但是,它不起作用.当我运行编码时,没有任何反应或弹出错误.请帮忙
编辑编码:
If ShiftName Like "*" & CashName & "*" Then
CashName.Font.Strikethrough = True
Run Code Online (Sandbox Code Playgroud)
三角形部分已经解决,并且在我将声明从"字符串"更改为"范围"之后不再显示"编译错误",如John Coleman所提议的那样.
我通过将Name1和Name2更改为两个Sally进行测试,然后使用以下条件进行删除并且它可以工作.我相信正是"*"使得这个条件变得不可行.
If ShiftName Like CashName Then
CashName.Font.Strikethrough = True
Run Code Online (Sandbox Code Playgroud)
如何通过相应地改变条件来完成部分匹配?
第二次编辑:
我的错!我意识到我的名字1在CAPTIALS中.
除了@MacroMan 关于 using 的回答之外Like,您还需要Strikethrough正确使用。它是一个布尔属性,需要设置为 True:
If Name1 Like "*" & Name2 Then
Name2.Font.Strikethrough = True
Exit Do
Else
End If
Run Code Online (Sandbox Code Playgroud)
在编辑:
根据您扩展的问题,您可以执行以下操作:
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
Run Code Online (Sandbox Code Playgroud)
.Value在范围变量上使用并不是绝对必要的(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
Run Code Online (Sandbox Code Playgroud)
最后一句话:Else紧接其后的End If有点毫无意义。大概你的实际代码在 else 子句中做了一些事情。如果不是 - 只需完全删除 else 并End If立即在Exit Do
| 归档时间: |
|
| 查看次数: |
12829 次 |
| 最近记录: |