I am new to VBA and I would like to do a partial string (or cell) match between two sheets.
An example of Name1 would be \"IT executive Sally Lim\"
An exampl
Use the Like
operator:
If Name1 Like "*" & Name2 Then
You can use Like
for specific pattern matching, but it also allows the wild character *
In addition to @MacroMan 's answer about using Like
, you would also need to use Strikethrough
correctly. It is a Boolean property which needs to be set to True:
If Name1 Like "*" & Name2 Then
Name2.Font.Strikethrough = True
Exit Do
Else
End If
On Edit:
Based on your expanded question, you could do something like this:
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
It isn't strictly necessary to use .Value
on Range variables (the comparison using Like
would work as expected without it) but it is considered by many to be good VBA coding style to be explicit when using range variables as opposed to relying on the default property of range objects.
You could also dispense with the variables Name1
and Name2
entirely:
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
A final remark: The Else
followed immediately by End If
is somewhat pointless. Presumably your actual code does something in the else clause. If not -- just delete else entirely and have End If
immediately after the Exit Do