Find Text and Replace with Formula using VBA

Trikageon

Board Regular
Joined
Apr 29, 2010
Messages
51
Hey all! I'm looking for a code in my macro that will search out a text in a given range and replace it with a formula. For example:

In column G, I want to find and replace every instance of the word "Total" (a stand-alone word, not part of a formula) with a formula similar to =SUMIF(O:O,"Total"&N17,G:G)

Now, I say similar to because, the N17 is a relative reference, which is effectually saying I want the word "Total," in this formula, to concatenate with the cell that's 2 rows up and 7 columns over from the cell that's being evaluated

Any ideas?
 

Excel Facts

Show numbers in thousands?
Use a custom number format of #,##0,K. Each comma after the final 0 will divide the displayed number by another thousand
Record a macro while entering that formula. Excel will use the FormulaR1C1 property and the R1C1 reference style, which is what you need.
 
Upvote 0
Try:

Code:
Dim rng As Range
 
With ActiveSheet.Range("G:G")
  Set rng = .Find(What:="Total",LookAt:=xlWhole,LookIn:=xlValues)
 
  If Not rng Is Nothing Then
    Do
      rng.FormulaR1C1 = "=SUMIF(C15,""Total""&R[-2]C[7],C7)"
      Set rng = .FindNext(rng)
    Loop While Not rng Is Nothing
  End If
End With
 
Upvote 0
Ok, that worked great, except I'm getting an error at the end...it points to this when I debug:

Set rng = .FindNext(rng)

Also, what would I do if I also wanted to include column H?
 
Upvote 0

Forum statistics

Threads
1,223,911
Messages
6,175,327
Members
452,635
Latest member
laura12345

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top