5

So, I have the following short code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    'More code here    

    If Target.Cells.Count > 1 Or Target = Empty Then
       Exit Sub
    End If

    'More code here.
End Sub

Instead of evaluating A and then B if the A part is false, it is evaluating both at the same time, which is something I don't recall vba doing before.

Sorry If my explanation is not good enough, english if not my native language. Be comprehensive and constructive, please. I had many bad experiences with comments here lately.

Lorthas
  • 376
  • 3
  • 11
  • 2
    I don't recall VBA not doing it. Consider that you weren't aware of it since it never backfired. The 'workaround' in this case is fairly simple (two lines). 1.) `If Target.Cells.CountLarge > 1 Then Exit Sub`, 2.) `If IsEmpty(Target) Then Exit Sub`. Actually, you only need to change to `IsEmpty(Target)` to avoid the type mismatch error. – VBasic2008 Apr 23 '22 at 10:27
  • 1
    Please update your post to include the definition of Target. – freeflow Apr 23 '22 at 11:01
  • 3
    Just to make @VBasic2008 comment clearer. VBA does not, and has never, supported short circuiting. This is why VB.Net includes AndAlso, and OrElse. As an aside, twinBasic, the up and coming alternative for VBA, also support AndAlso and OrElse. – freeflow Apr 23 '22 at 11:07
  • I don't mean to offend you but you seem to be looking for short-circuit evaluation in VBA. Imagine this would exist (which is not the case, by the way), wouldn't it be better to switch both conditions, something like `Target = Empty Or Target.Cells.Count > 1`? – Dominique Apr 29 '22 at 06:48

1 Answers1

0

You can find the answer here:

  1. Does the VBA "And" operator evaluate the second argument when the first is false?
  2. AndAlso/OrElse in VBA

In short, there's no native short-circuit evaluation of logical expressions in VBA. But you can do it with the Select Case operator. Look here for more information on the topic https://en.wikipedia.org/wiki/Short-circuit_evaluation

p.s. In your case, I would take VBasic2008's advice.

Vitalizzare
  • 4,496
  • 7
  • 13
  • 32
  • You should add a 'flavor' of 'my advice' to your answer to improve it. I mean it's kind of common knowledge, not something I discovered (invented). – VBasic2008 Apr 23 '22 at 11:33