I'm fairly new to VBA. I'm working on an Excel project and I keep seeing 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 these cases in particular, could there be any reason whatsoever for checking if the property is set before setting it, or is this just a useless check? Surely the VBA engine must make an internal check so that it doesn't do anything needlessly.
I think I know the reason someone made the code you analyse. The source of such situation comes possibly from book of Bovey, Rob/ Wallentin, Dennis/ Bullen, Stephen/ Green, John titled: "Professional Excel Development: The Definitive Guide to Developing Applications Using Microsoft Excel and VBA, and .NET" which chapters (or complete) you could possible find in the Internet. There is a chapter dedicated to micro- and macro-optimisation. Let's me quote one which refers to your question:
Test a Property Before Setting It
It is often much faster to read a property than to write it. It can save time to only update a property when it needs to change, by checking whether it has the required value first. For example, reading the value of Range.Font.Bold and only setting it to True if it isn’t True already. This contradicts the general rule of reducing the amount of code you write, but it will provide a significant performance increase if it allows you to avoid setting properties unnecessarily.
I will not confirm whether its true or not. But I rather trust authors of the book.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With