I'm having a problem with Range.Replace. As we all know, when in the Excel worksheet interface we can Find & Replace with Match Case set to True or False, and when we Find or Replace again Excel remembers our Match Case setting. The same is true if we use Find & Replace from VBA, and for other settings such as LookIn, LookAt.
Note that Find & Replace using the Excel worksheet interface also remembers the "Within" option (set to either "Sheet" or "Workbook"). My problem is that if I have used Find & Replace from the worksheet interface and I have set the "Within" option to "Workbook" (instead of the default "Sheet"), then Excel VBA also remembers that option, and does a Workbook-level Replace even if I am invoking Range.Replace (ie I only want the Replace to happen over a specific range).
I can reproduce as follows:
- Create new workbook with three empty sheets.
- In sheet 1 enter "this" in $A$1; in sheet 2 enter "that" in $A$1.
- Do a Find for "junk" with "Within" set to "Workbook" and leave all other options unchecked and default. This will find nothing; close the dialogue.
- In sheet 3, select a range eg $A$1:$K$10 and leave this sheet active.
- Open the VB Editor and enter:
Selection.Replace "th","help"
.
You will find (well, I did) that even though we are using a Range.Replace the instances of "th" on the inactive sheets 1 and 2 have been changed -- so it seems that the "Within" choice has been remembered and the "Range" part of "Range.Replace" is being ignored.
Is there any way to override this? Or force Excel to forget the "Within" setting?
I am using Office Professional Plus 2016 on Windows 10.
Please help!
Find
the value first on the sheet in question, and thenReplace
.... quick Google search: vbaexpress.com/forum/…, and ozgrid.com/forum/forum/help-forums/excel-general/… – BigBenRange.Find
call. – Mathieu GuindonRange.Replace
overSelection
. – Mathieu GuindonSelection
. I'm not sure I'd call it a bug, but sinceWithin
in the Find/Replace dialog is not an optional parameter, I think the VBA solution to coerce the replace to a Sheet is to doSheet.Range.Find
first, and thenReplace
. – BigBenRange.Find
orRange.Replace
without specifying the optional parameters, is begging for things to go wrong: silly as it is, these methods are literally specified to "remember" the values for these optional parameters, and to reuse them when not specified (regardless of the "Within" issue). UsingSheet1.Cells.Find
effectly seems to "resets" the "Within" from "Workbook" to "Sheet" when I try it, hence my suspicion aboutSelection
, which I hardly ever use at all. – Mathieu Guindon