Use of If statement with multiple conditions

前端 未结 6 2027
挽巷
挽巷 2021-01-15 23:54

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

6条回答
  •  不思量自难忘°
    2021-01-16 00:17

    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.

提交回复
热议问题