vba If...Then...Else 在 Then 之后有多个语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15459576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:10:27  来源:igfitidea点击:

If...Then...Else with multiple statements after Then

vbaif-statementconditional-statements

提问by Avitus

a very easy question: considering an If...Then...Elseinstruction in VBA, how can I separate multiple instructions after Then? In other words, should I write something like

一个非常简单的问题:考虑If...Then...ElseVBA 中的一条指令,如何在 之后分离多条指令Then?换句话说,我应该写一些像

If condition [ Then ]    
   [ statement1 ] & [statement2] 
Else [Else statement] (i.e. using "&"),

or

或者

If condition [ Then ]         
   [ statement1 ] And [statement2] 
Else [Else statement] (i.e. using "And"),

or some other separator/command?

或其他一些分隔符/命令?

回答by NGLN

Multiple statements are to be separated by a new line:

多条语句用新行分隔:

If SkyIsBlue Then
  StartEngines
  Pollute
ElseIf SkyIsRed Then
  StopAttack
  Vent
ElseIf SkyIsYellow Then
  If Sunset Then
    Sleep
  ElseIf Sunrise or IsMorning Then
    Smoke
    GetCoffee
  Else
    Error
  End If
Else
  Joke
  Laugh
End If

回答by user4852244

This works with multiple statements:

这适用于多个语句:

if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6

Or you can split it over multiple lines:

或者您可以将其拆分为多行:

if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6