0

I have a sheet with formulas containing the text "apple". I want to do the following:

  1. Replace every instance of the word apple in this sheet with "banana"
  2. print results (simple copy and paste)
  3. Replace banana with "cats"
  4. print results (simple copy and paste)
  5. Replace "cats" with "dogs"
  6. print results (simple copy and paste)
  7. Finally end with restoring base case i.e. replace "dogs" with apple"

I've got the first iteration working (see below) just need help on how to implement the loop.

Thanks in advance!!

Sub FindReplaceAll()

Dim sht As Worksheet
Dim fnd As Variant
Dim rplc As Variant

fnd = "apple"
rplc = "banana"

'Store a specfic sheet to a variable
  Set sht = Sheets("Trace")

'Perform the Find/Replace All
  sht.Cells.Replace what:=fnd, Replacement:=rplc, _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
    
Range("ResFinal").Copy
    Worksheets("Results").Activate
    Range("E13").PasteSpecial xlPasteValues
   
End Sub

1 Answer 1

1

You could put the items into two arrays and loop through them, viz

Sub FindReplaceAll()

Dim sht As Worksheet
Dim fnd As Variant
Dim rplc As Variant
Dim i As Long

fnd = Array("apple", "banana", "cats", "dogs")
rplc = Array("banana", "cats", "dogs", "apple")

'Store a specfic sheet to a variable
Set sht = Sheets("Trace")

'Perform the Find/Replace All
For i = LBound(fnd) To UBound(fnd)
    sht.Cells.Replace what:=fnd(i), Replacement:=rplc(i), _
        LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
        SearchFormat:=False, ReplaceFormat:=False
    Range("ResFinal").Copy
    Worksheets("Results").Range("E13").PasteSpecial xlPasteValues
Next i

End Sub
Sign up to request clarification or add additional context in comments.

4 Comments

Could also use a 2-dimension array instead of 2 separate arrays
Hey SJR, thank you so much for your response! This will work! If I wanted to offset the print (copy and pate) by a row each time i.e. E13 for banana, E14 for cats... and then for the restore to base case there is no print, how would I go about this.
My pleasure. You could use Worksheets("Results").Range("E13").offset(i).PasteSpecial xlPasteValues.
I just tried the above approach and created a new sub to restore the base case without print (i.e. change dogs to apple without a copy and paste command) - Thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.