2

i have maybe a simple question, but its blowing my mind. I have some code to refactor it a bit, but cant figure out what author thinks by this statement

If (j > 0) Then greatThanPrec = greatThanPrec And (signalAmplArray(i) > signalAmplArray(j))

I think i know how basic If Then else works, but cant realize why is something like A = A after then, and then is AND maybe some short condition like in C/C++?

Luboš Suk
  • 1,526
  • 14
  • 38
  • 1
    no, it's a **logical** (bitwise) AND. Then it means that "if the condition is met, change the value of A to `A And B`". – Phantômaxx Apr 27 '16 at 07:23
  • `And`, `Or` are Boolean (True/False) operators. The `greatThanPrec` is a Boolean type here. – PatricK Apr 27 '16 at 07:25
  • 2
    @PatricK In VBA, `And` and `Or` are bitwise. They work just as fine in logical contexts, but they are inherently bitwise (as opposed to `AndAlso` and `OrElse` in VB.NET). – GSerg Apr 27 '16 at 07:31
  • @GSerg Thanks, didn't notice it before. I can confirm in immediate window with `?1 Or 2` (=3) and `?2 And 3` (=2). This opens up some tweaks for some calculations for me. – PatricK Apr 27 '16 at 23:01

1 Answers1

9

That particular And has nothing to do with If Then.

The code after Then simply updates greatThanPrec depending on whether signalAmplArray(i) > signalAmplArray(j) or not. greatThanPrec will stay True if both greatThanPrec and signalAmplArray(i) > signalAmplArray(j) are True, otherwise it will become False.

To better see it, replace signalAmplArray(i) > signalAmplArray(j) with its possible values. You will get two options:

greatThanPrec = greatThanPrec And True  'greatThanPrec does not change its value
greatThanPrec = greatThanPrec And False 'greatThanPrec becomes false

If you want to refactor it, that would be

If (j > 0) Then
  If Not (signalAmplArray(i) > signalAmplArray(j)) Then
    greatThanPrec = False
  End If
End If
GSerg
  • 76,472
  • 17
  • 159
  • 346
  • Is the AND here a logical Connector or does it just Connet two Lines after the Then? – Moosli Apr 27 '16 at 07:33
  • 2
    `And` never connects two lines. You use `:` in VBA to put multiple statements on one line. That is, you can write code where you have boolean functions that have side effects, and you can call them on one line like `= CauseEffects() And CauseMoreEffects()`, but that is both not what is happening here and is bad code, especially for people who don't realize VBA [does not have short circuit](http://stackoverflow.com/q/3242560/11683). – GSerg Apr 27 '16 at 07:36
  • @Moosli the And here is a Logical conjunction yes. – Doktor OSwaldo Apr 27 '16 at 07:38
  • @Gserg: Thanks for the explanation and the Link. I learned something new – Moosli Apr 27 '16 at 07:44
  • @GSerg thanks for great answer ;) didnt thought its so simple – Luboš Suk Apr 27 '16 at 11:56