I have two lists of names on an excel sheet (sh1 - Column A, Column D)
. On another excel sheet (sh2 - Column B)
, I have a another list of names. I am trying to find/replace Column A names on Column B with Column D.
My full code is listed at the bottom. I am getting a "Subscript out of range" error on this line:
Selection.Replace What:=fndArr(i), Replacement:=rplArr(i), LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
ReplaceFormat:=False
I have checked the range and it seems like the code should loop through every cell in sh2 Column B looking for Column A data and replacing it with Column D data.
I'm drawing a total blank on this. Does anyone know why I am getting this error? Thank you for your help.
Column A | Column B | Column D
--------------------------------------------
Hugh Jackman | Hugh J | Hugh Jackman
Ronald Reagan | Ronald R | Ronald Reagan
John Adams | John A | John Adams
.
Sub CheckReplace()
Dim sh1 As Worksheet, sh2 As Worksheet
Dim fndArr() As Variant
Dim rplArr() As Variant
Set sh1 = Sheets("CA")
Set sh2 = Sheets("FD")
''' turn off screen updating '''
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
''' Find/Replace CA '''
sh1.Activate
fndArr = sh1.Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row)
rplArr = sh1.Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row)
sh2.Activate
Columns("B").Select
For i = 0 To UBound(fndArr)
Selection.EntireColumn.Select
Selection.Replace What:=fndArr(i), Replacement:=rplArr(i), LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
ReplaceFormat:=False
Next i
''' turn on screen updating '''
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
EDIT:
The following change in code allows it to run without throwing an error, but then it find/replaces the first values in Column A/B, e.g. Hugh Jackman Hugh J, but not Ronald Reagan, Ronald R:
fndArr = Array(sh1.Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row))
rplArr = Array(sh1.Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row))