Rubberduck icon indicating copy to clipboard operation
Rubberduck copied to clipboard

Improving calls to Range.Find (and other methods where default arguments use saved settings)

Open ThunderFrame opened this issue 9 years ago • 0 comments

The Range.Find method has only one required argument, but an additional 4 arguments default to the value used most previously by the user (regardless of whether it is through VBA or the UI), which can result in different behavior from one user to another, and from one Find call to the next.

The settings for LookIn, LookAt, SearchOrder, and MatchByte are saved each time you use this method. If you do not specify values for these arguments the next time you call the method, the saved values are used. Setting these arguments changes the settings in the Find dialog box, and changing the settings in the Find dialog box changes the saved values that are used if you omit the arguments. To avoid problems, set these arguments explicitly each time you use this method.

Rubberduck will need to special case these arguments as something like OptionalButNecessary and offer an inspection to fix the calls.

A courteous solution would persist the current settings, make the Range.Find call with specific arguments, and then restore the persisted settings, but I'm unsure how feasible this is.

There are other methods with arguments that behave the same way, such as Range.TextToColumns, although the documentation for TextToColumns doesn't reflect (or warn about) the actual behavior. In practice, for example, if a delimiter isn't passed as an argument, TextToColumns uses the most recently used delimiter for the user.

For example, the boolean delimiter arguments can be one of Tab, Semicolon, Comma, Space, or otherwise Other (in which case, the OtherChar argument becomes mandatory). The documentation says they're all optional* and they all default to False, but in reality, if none is specified, the most recently used value is used.

Rubberduck will probably need to special case such arguments as something like OptionalButNecessaryUnion, along with a group name to determine the mutually exclusive members)

My own preference in this particular case, is to always treat Other and OtherChar as required, and treat Tab, Semicolon, Comma and Space as an ambiguous mess useless.

There are undoubtedly other methods that behave in the same way.

Linking #2332

ThunderFrame avatar Oct 27 '16 21:10 ThunderFrame