Mac – Excel macro: Replace enitre cell contents; replace 1 but not 10, 11, 21 etc

find and replacemacrosmicrosoft excel

I need to replace a large amount of numbers with words in an Excel spreadsheet.
Eg:

1 = hello
12 = goodbye
4 = cat

etc. I can do it with the standard search and replace, but I have a large list to work through (about 240 number/word combos), so i figured I would use a macro.

I have this:

Sub findreplacer()
For Each mycell In Range("A1:A1000")
mycell.Replace What:="1", Replacement:="hello"
mycell.Replace What:="12", Replacement:="goodbye"
mycell.Replace What:="4", Replacement:="cat"
Next

End Sub

But it replaces the 1 in 12 so the cell reads hello2 instead of goodbye.
How can I make it just affect cells that only contain the specific number, the way 'match entire cell contents' works?

Any help appreciated.

Best Answer

Changing the order is fine, so long as every value in the sheet is going to be replaced. If your sheet contained 11 though that wasn't going to be replaced then changing the order will still replace it with hello1.
To use match entire cell specify

,LookAt:=xlWhole

as another parameter to the Replace method. Replace is a valid method on a Range so your For loop is not necessary. You can instead specify

Range("A1:A1000").Replace What:="12", Replacement:="goodbye", LookAt:=xlWhole  
Range("A1:A1000").Replace What:="4", Replacement:="cat", LookAt:=xlWhole
Related Question