Excel/Replace cell with different text
QUESTION: Hi Adelaide,
I got the following code from Tom Ogilvy in 2008:
for each cell in worksheets("Sheet2").Range("A1:A100")
worksheets("Sheet1").Columns(5).Replace what:=cell, _
' use xlwhole if you want to match a whole cell
At the moment the code looks for all the data in the first column and then changes it to the replacement data in the second column.
Is there a way to get the code to look at parts of the data in the first column?
ANSWER: Hi Michael
How are you?
Please have a look at this:
For Each cell In Worksheets("Sheet2").Range("A1:A100")
Worksheets("Sheet1").Columns(5).Replace what:=Mid(cell, 1, 2), Replacement:=cell.Offset(0, 1), Lookat:=xlPart,SearchOrder:=xlByRows, MatchCase:=False
It replaces the 2 first characters of each cell in E1:E100 ------- what:=Mid(cell, 1, 2)-------of sheet1 that match those of A1:A100 of sheet 2 with the corresponding value of B1:B100 of sheet2
I Hope this helps.
[an error occurred while processing this directive]---------- FOLLOW-UP ----------
Thanks for that, but it doesn't do what i really wanted it to do. I have the following in sheet 2 column 1: RESISTOR CHIP 0603 2K4 1% 1/16TH WATT and this in sheet 2 column 2: 2K4-0603-RES;*;. What i was after was it only looking for a part of: RESISTOR CHIP 0603 2K4 1% 1/16TH WATT to give a result of: 2K4-0603-RES;*;. At the moment it needs to see the whole of: RESISTOR CHIP 0603 2K4 1% 1/16TH WATT to work at all. I thought that using xlPart meant that it was only searching some of the cell.
I just looked through the original code i sent you and the line: worksheets("Sheet1").Columns(5).Replace what:=cell, _ should be worksheets("Sheet1").Columns().Replace what:=cell, _
How are you?
Either you play around with the argument What:=MID(cell, start character, number of charaters) ... the exemple I attached Mid(cell, 1,2) looks for the first 2 characters of cell ("Re" of Resistor ) and makes the replacement.
(you have to know which substring is the key for the replacement - the number of charaters and the start position on the string)
the vba program gives up the replace instruction and asks the user for the substring to search and performs the replacement whenever the criteria matches.