I am working on a <acronym title="visual basic for applications">VBA</acronym> to Find from Column B (Sheet 2) and Find in (Sheet 1) and Replace the value = Column B in Sheet 2 of which = Column A (the replacement value.) When I run the macro it works, but I have multiple values = to the same value in Column B and it is only choosing one of those values to replace. How do I write this code to let it replace with multiple values it is equal to.
Here is the code:
Option Explicit
Option Compare Text
Sub FIND_AND_REPLACE()
On Error Resume Next
Application.ScreenUpdating = False
Dim toFind As String, toReplace As String, rng As Range, cel As Range, i As Long, frow As Long, _
frowT As Long, wk As Worksheet, ws As Worksheet, j As Long
Set wk = Sheet1: Set ws = Sheet2
frow = wk.Range("AM" & Rows.Count).End(xlUp).Row
frowT = ws.Range("A" & Rows.Count).End(xlUp).Row
Set rng = wk.Range("AM2:AQ" & frow)
For i = 2 To frowT
toFind = ws.Range("B" & i).Value
toReplace = ws.Range("A" & i).Value
rng.Replace What:=toFind, Replacement:=toReplace, LookAt:=xlWhole, MatchCase:=False
Next i
For i = 2 To frow
wk.Range("AR" & i) = ""
For j = 39 To 43
If Trim(wk.Cells(i, j)) <> "" Then
wk.Range("AR" & i) = wk.Range("AR" & i) & "," & Trim(wk.Cells(i, j))
End If
Next j
If Trim(wk.Range("AR" & i)) <> "" Then
wk.Range("AR" & i) = Right(wk.Range("AR" & i), Len(wk.Range("AR" & i)) - 1)
End If
Next i
Application.ScreenUpdating = True
MsgBox "Done"
End Sub
Here is the code:
Option Explicit
Option Compare Text
Sub FIND_AND_REPLACE()
On Error Resume Next
Application.ScreenUpdating = False
Dim toFind As String, toReplace As String, rng As Range, cel As Range, i As Long, frow As Long, _
frowT As Long, wk As Worksheet, ws As Worksheet, j As Long
Set wk = Sheet1: Set ws = Sheet2
frow = wk.Range("AM" & Rows.Count).End(xlUp).Row
frowT = ws.Range("A" & Rows.Count).End(xlUp).Row
Set rng = wk.Range("AM2:AQ" & frow)
For i = 2 To frowT
toFind = ws.Range("B" & i).Value
toReplace = ws.Range("A" & i).Value
rng.Replace What:=toFind, Replacement:=toReplace, LookAt:=xlWhole, MatchCase:=False
Next i
For i = 2 To frow
wk.Range("AR" & i) = ""
For j = 39 To 43
If Trim(wk.Cells(i, j)) <> "" Then
wk.Range("AR" & i) = wk.Range("AR" & i) & "," & Trim(wk.Cells(i, j))
End If
Next j
If Trim(wk.Range("AR" & i)) <> "" Then
wk.Range("AR" & i) = Right(wk.Range("AR" & i), Len(wk.Range("AR" & i)) - 1)
End If
Next i
Application.ScreenUpdating = True
MsgBox "Done"
End Sub