0

I have a table in sheet 1 has two columns A and B. I created a macro to find the value of A1 in sheet 2 and replace the value of B1 instead of value A1 in sheet 2

I am looking to improve the macro to cover the whole range of A and B columns.

    Sub Find_Replace()
'

'
    Sheets("Sheet1").Select
    Range("A1").Select
    Selection.Copy
    Sheets("Sheet1").Select
    Range("B1").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Sheet2").Select
    Selection.Replace What:="Value 1 ", Replacement:="value X", LookAt:= _
        xlPart, SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
End Sub

sample table

** looking to improve Range("A1").Select to cover all available cells in range A and B

1
  • In this process you may accidentally re-replace certain cells in Sheet2 if the already replaced value in that cell occurs elsewhere in Column A in Sheet1. e.g. You would replace occurrences of "value 2" (Sheet1.A2) with "value r" (Sheet1.B2) actually in Sheet2 columns say A, B & C, now if "value r' as a string occurs in subsequent cell of Column A in Sheet1 it will be again searched and replaced with its counterpart from Sheet1.ColumnB . Is that OK with you?
    – patkim
    Commented Nov 12, 2017 at 19:20

1 Answer 1

0

Try this code. Sample range is A1:A10 in Sheet1. B1:B10 is automatically referred using Offset method in the VBA code. However the limitation as I mentioned in the above comment applies. Sheets are Sheet1 and Sheet2 in the same workbook.

Do try this code and revert back.

Sub Macro1()
Set myrange = Sheet1.Range("A1:A10")
For Each cell In myrange

Dim find1
Dim replace1

find1 = cell.Value
replace1 = cell.Offset(RowOffSet:=0, ColumnOffset:=1).Value

    Sheet2.Cells.Replace What:=find1, Replacement:=replace1, LookAt:=xlPart, SearchOrder _
        :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

Next cell
End Sub

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .