0

I'm working with some checkboxes on a userform, and am checking if they have been checked by the user in my code. The question I'm running into is in how to properly check for this condition. I've found several examples, and am wondering where I may run into trouble with each.

For example, I have seen several snippets use:

If checkBox1.Value = "True" Then

or

If checkBox1.Value Then

or

If checkBox1 Then

Is there any functional difference between these? It seems like the latter is the shortest, most succinct application, however the engineer's brain in me is saying there must be a reason for the other two cases (although the more I work with VBA, the less I believe in that concept).

Any assistance or guidance you could provide would be appreciated.

Jon Torsch
  • 15
  • 1
  • 5

2 Answers2

0

I would recommend the second one. It is always best to specify the property of an object explicitly rather than relying on defaults. There is no point in comparing a Boolean to True/False, since it already is True or False, and there is less point comparing it to a String value (which would be different in different regions).

Rory
  • 32,730
  • 5
  • 32
  • 35
0

In this case they are all the same and can be used interchangeably. Yet, I would only use the first or the second option.

checkBox1 is essentially incomplete and VBA automatically assumes (for you) that you are referring to its value and hence "completes" (during run-time) your code to checkBox1.Value. This takes time and may essentially slow down your code (even if this is barely noticeable).

To most programmers the second option is the preferred option because the if statement evaluates if something is True or False. Since the .Value of the checkbox is already True or False the first option is unnecessarily long. The value of checkbox1 is alredy True. So, why would you compare it to True?

At the same time I always prefer to use the first option as it makes the code easier to read for me (personal preference).

So, I'd say option 1 or 2: it's your choice.

Ralph
  • 9,284
  • 4
  • 32
  • 42
  • Do you have a source for accessing default properties slowing down code execution? I've never heard of that. – Kyle Mar 16 '16 at 14:48
  • I did my own testing a while back with 500.000 rows comparing the use of `.Value`, `.Value2`, and ` ` with Office 2010. It was the traditional `.Value` vs `.Value2` I wanted to verify myself. But I have never seen the comparison to ` ` (forcing VBA to auto complete with the default). The time differences was rather minimal compared to the differences between `.Value` and `.Value2` and [had to be calculated in milliseconds](http://stackoverflow.com/questions/939230/how-to-get-a-datediff-value-in-milliseconds-in-vba-excel). Hence (and since I don't have a website) I never posted my findings. – Ralph Mar 16 '16 at 15:11