Home » excel » excel – How to define 'Within' match criteria using VBA Find or Replace function?

excel – How to define 'Within' match criteria using VBA Find or Replace function?

Posted by: admin May 14, 2020 Leave a comment


There are similar questions regarding this, but none address my issue.

I have a tool that is basically a bulk find/replace. I define a set ‘template’ of data with keyword placeholders in it, then provide a list of template instance definitions that define values for these placeholders, and the tool simply copies the template as many times as I have template instances, and find/replaces the placeholders as it goes.

The find/replace code uses:

Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
For iParam = LBound(gsaXMLParams) To UBound(gsaXMLParams)
    Selection.Replace What:=gsParamSymbol & gsaXMLParams(iParam) & gsParamSymbol, Replacement:=gsaXMLParamVals(iInstance, iParam), LookAt:=xlPart, _
                SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _

I only want to replace the current sheet. The trouble is, there is no ‘Within’ argument in the Replace function, and instead the replace function uses the currently set ‘Within’ criteria as set in the Excel Find/Replace tool. If this is set to ‘Workbook’, then all of my sheets have their cells replaced (if matching replace criteria).

I have tried using Range.Replace as well which produces the same issues.

enter image description here

How do I set the ‘Within’ criteria programmatically??

Example data:
E.g. Template:


E.g. Template Instance Definitions

Area     SiteName
Area 1   John's Town
Area 2   Peter's Town

E.g. Output

Area 1.John's Town.Metering.Value
Area 2.Peter's Town.Metering.Value
How to&Answers:

The ‘within’ you are speaking of is the Range.Replace Method‘s parent.

When you use Range(“A1”).Font.Color = vbRed, you are setting the color of the font of A1 so Color is a Property of Font and Font is a Property of Range, specifically, Range(“A1”).

So if you use the Worksheets(“Sheet1”).Cells.Replace what:=…, replacememt:=…, method, you are performing it on the cells in Sheet1, and only those cells just as setting the font color in the earlier example only set a red font in A1. Currently you are making the replacement on whatever is selected.


Doing a little more Googling, there doesn’t look like there’s a ‘proper’ solution, however using the first line of the following before any Replace calls will reset the Find/Replace tool options, including resetting Within to ‘Sheet’:

Set r = Worksheets(1).Range("A1").Find(What:="This will reset the Find/Replace tool options, including setting Within=Sheet")