Is there any reason to check if a property is set before setting it?

I am new to VBA. I am working on an Excel project and I see the code in the project that looks like this:

If Me.Columns(i).Hidden = True Then Me.Columns(i).Hidden = False End If 

and this:

 If Range("SomeRange").Locked = True Then Range("SomeRange").Locked = False End If 

In such cases, in particular, can there be any reason to check whether the property is set before setting it, or is it just a useless check? Of course, the VBA engine needs to do an internal check so that it doesn't do anything unnecessarily.

+6
source share
2 answers

I think I know why someone made the code you are analyzing. The source of this situation may be the book by Bovey, Rob / Wallentin, Dennis / Bullen, Stephen / Green, John entitled "Excel Professional Development: The Ultimate Guide to Developing Applications Using Microsoft Excel and VBA and .NET," which chapters (or full) can be found on the internet. There is a chapter on micro and macro optimization. Let me give a quote that refers to your question:

Check property before setting

Often much faster to read than to write. This can save time to update the property when it needs to be changed by checking if it has the required value first. For example, reading the value of Range.Font.Bold and only setting it to True if it is no longer True. This contradicts the general rule of reducing the amount of code that you write, but this will provide a significant increase in performance, if this avoids without additional settings.

I will not confirm whether this is true or not. But I rather trust the authors of the book.

+5
source

This is probably a worthless check. I don’t see the big reason why you will have extra checking if there isn’t any other logic when a particular column / row is hiding.

+1
source

Source: https://habr.com/ru/post/950646/


All Articles