I have written the following code which is basically supposed colour some boxes accordingly. Whenever i run this code, it runs the first case i.e. even when some other case
The answer to your problem lies in the fact that the numbers in your Or
conditions are implicitly coerced to Boolean values, and that when this happens, everything except 0 is coerced to True
. To convince yourself of this, try Debug.Print CBool(13)
and Debug.Print CBool(0)
.
I am a bit peeved that none of the people who have posted previous answers have explained this, hence this post which might otherwise have been considered repetitive!
Instead of
If Sheet2.Range("B6").Value = 1 Or 2 Or 3 Then
use
If Sheet2.Range("B6").Value = 1 Or _
Sheet2.Range("B6").Value = 2 Or _
Sheet2.Range("B6").Value = 3 Then
etc. Or, even better, a Select Case
construct as suggested by @mwolfe02.