Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

excel

vba

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.

like image 393
Anthony Avatar asked Jul 30 '13 18:07

Anthony


1 Answers

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.

like image 74
Kazimierz Jawor Avatar answered Nov 15 '22 06:11

Kazimierz Jawor