If Statement With Multiple Lines

佐手、 提交于 2019-11-29 02:55:01

The VBA line-continuation character is an underscore _

if ( _
    (something) _
    or (somethingelse) _
) 

You can use the line continuation character _

These are all the same:

If Something Or  SomethingElse Or AnotherThing Then

If Something Or SomethingElse _
   Or AnotherThing Then

If Something Or _
   SomethingElse Or _
   AnotherThing Then

Like the above, you can break up the long set of conditions in one "IF" statement by using an underscore.

If there are too many conditions and I find it challenging to read, I use BOOLEANS to represent the conditions. It seems like there is more code, but I find it easier to read.

If I have a scenario where I need to do the following:

IF (X = something1) OR (X = something2) OR (X = something2) OR (X = something2) OR (X = something2) OR (X = something2) OR (X = something2) OR (X = something2) THEN
END IF

I could do this:

IF _
    (X = something1) _
    OR (X = something2) _
    OR (X = something3) _
    OR (X = something4) _
    OR (X = something5) _
    OR (X = something6) _
    OR (X = something7) _
    OR (X = something8) _
THEN
END IF

... or I could do this ...

blnCondition1 = (X = something1)
blnCondition2 = (X = something2)
blnCondition3 = (X = something3)
blnCondition4 = (X = something4)
blnCondition5 = (X = something5)
blnCondition6 = (X = something6)
blnCondition7 = (X = something7)
blnCondition8 = (X = something8)

IF blnCondition1 OR blnCondition2 OR blnCondition3 OR blnCondition4 OR blnCondition5 OR blnCondition6 OR blnCondition7 OR blnCondition8 THEN
END IF

Of course, the example BOOLEAN variables are defined, and instead of names like blnCondition1, I'll use meaningful names.

Again, it's just a preference I have.

DevilWAH

break them with an under score _ ?

Microsoft Library

from above link

If ActiveSheet.ChartObjects(1).Chart.ChartTitle = _
      ActiveSheet.Range("a2").Value Then
   MsgBox "They are equal."
End If

im pretty sure you can use an underscore _ to break up lines.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!