- If. Then. Else Statement (Visual Basic)
- Syntax
- Quick links to example code
- Parts
- Remarks
- Multiline syntax
- Single-Line syntax
- Multiline syntax example
- Nested syntax example
- Single-Line syntax example
- Директива #If. Then. #Else #If. Then. #Else directive
- Синтаксис Syntax
- Примечания Remarks
- Пример Example
- См. также See also
- Поддержка и обратная связь Support and feedback
- Использование операторов If. Then. Else Using If. Then. Else statements
- Выполнение операторов, если условие равно True Running statements if a condition is True
- Выполнение определенных операторов, если условие равно True, и выполнение других операторов, если оно равно False Running certain statements if a condition is True and running others if it’s False
- Проверка второго условия, если первое условие равно False Testing a second condition if the first condition is False
- См. также See also
- Поддержка и обратная связь Support and feedback
- if-else (Справочник по C#) if-else (C# Reference)
- Пример Example
- Пример Example
- Пример Example
- Спецификация языка C# C# language specification
If. Then. Else Statement (Visual Basic)
Conditionally executes a group of statements, depending on the value of an expression.
Syntax
Quick links to example code
This article includes several examples that illustrate uses of the If . Then . Else statement:
Parts
condition
Required. Expression. Must evaluate to True or False , or to a data type that is implicitly convertible to Boolean .
If the expression is a Nullable Boolean variable that evaluates to Nothing, the condition is treated as if the expression is False , and the ElseIf blocks are evaluated if they exist, or the Else block is executed if it exists.
Then
Required in the single-line syntax; optional in the multiline syntax.
statements
Optional. One or more statements following If . Then that are executed if condition evaluates to True .
elseifcondition
Required if ElseIf is present. Expression. Must evaluate to True or False , or to a data type that is implicitly convertible to Boolean .
elseifstatements
Optional. One or more statements following ElseIf . Then that are executed if elseifcondition evaluates to True .
elsestatements
Optional. One or more statements that are executed if no previous condition or elseifcondition expression evaluates to True .
End If
Terminates the multiline version of If . Then . Else block.
Remarks
Multiline syntax
When an If . Then . Else statement is encountered, condition is tested. If condition is True , the statements following Then are executed. If condition is False , each ElseIf statement (if there are any) is evaluated in order. When a True elseifcondition is found, the statements immediately following the associated ElseIf are executed. If no elseifcondition evaluates to True , or if there are no ElseIf statements, the statements following Else are executed. After executing the statements following Then , ElseIf , or Else , execution continues with the statement following End If .
The ElseIf and Else clauses are both optional. You can have as many ElseIf clauses as you want in an If . Then . Else statement, but no ElseIf clause can appear after an Else clause. If . Then . Else statements can be nested within each other.
In the multiline syntax, the If statement must be the only statement on the first line. The ElseIf , Else , and End If statements can be preceded only by a line label. The If . Then . Else block must end with an End If statement.
The Select. Case Statement might be more useful when you evaluate a single expression that has several possible values.
Single-Line syntax
You can use the single-line syntax for a single condition with code to execute if it’s true. However, the multiple-line syntax provides more structure and flexibility and is easier to read, maintain, and debug.
What follows the Then keyword is examined to determine whether a statement is a single-line If . If anything other than a comment appears after Then on the same line, the statement is treated as a single-line If statement. If Then is absent, it must be the start of a multiple-line If . Then . Else .
In the single-line syntax, you can have multiple statements executed as the result of an If . Then decision. All statements must be on the same line and be separated by colons.
Multiline syntax example
The following example illustrates the use of the multiline syntax of the If . Then . Else statement.
Nested syntax example
The following example contains nested If . Then . Else statements.
Single-Line syntax example
The following example illustrates the use of the single-line syntax.
Директива #If. Then. #Else #If. Then. #Else directive
Выполняет условную компиляцию выбранных блоков кода Visual Basic. Conditionally compiles selected blocks of Visual Basic code.
Синтаксис Syntax
#If выражение Then #If expression Then
Операторы statements
[ #ElseIf выражение-n Then [ #ElseIf expression-n Then
[ elseifstatements ]] [ elseifstatements ]]
[ #Else [ #Else
[ elsestatements ]] [ elsestatements ]]
#End If #End If
Синтаксис директивы #If. Then. #Else включает следующие части: The #If. Then. #Else directive syntax has these parts:
Часть Part | Описание Description |
---|---|
выражение expression | Обязательный. Required. Любое выражение, состоящее исключительно из одной или нескольких условных констант компилятора, литералов и операторов, оцениваемых как значение True или False. Any expression, consisting exclusively of one or more conditional compiler constants, literals, and operators, that evaluates to True or False. |
Операторы statements | Обязательная часть. Required. Строки программы Visual Basic или директивы компилятора, оцениваемые, если значение соответствующего выражения равно True. Visual Basic program lines or compiler directives that are evaluated if the associated expression is True. |
выражение-n expression-n | Необязательно. Optional. Любое выражение, состоящее исключительно из одной или нескольких условных констант компилятора, литералов и операторов, оцениваемых как значение True или False. Any expression, consisting exclusively of one or more conditional compiler constants, literals, and operators, that evaluates to True or False. |
elseifstatements elseifstatements | Необязательно. Optional. Одна или несколько линий программы или директивы компилятора, которые определяют, имеет ли выражение-n значение True. One or more program lines or compiler directives that are evaluated if expression-n is True. |
elsestatements elsestatements | Необязательный параметр. Optional. Одна или несколько линий программы или директивы компилятора, которые определяют, имеют ли выражение либо expression-n значение True. One or more program lines or compiler directives that are evaluated if no previous expression or expression-n is True. |
Примечания Remarks
Поведение директивы #If. Then. #Else аналогично заявлению If. Then. Else, за исключением случаев отсутствия однострочной формы директив #If, #Else, #ElseIf и #End If, т. е. никакой другой код не может появиться в той же строке, что и любая из директив. The behavior of the #If. Then. #Else directive is the same as the If. Then. Else statement, except that there is no single-line form of the #If, #Else, #ElseIf, and #End If directives; that is, no other code can appear on the same line as any of the directives.
Условная компиляция обычно используется для компиляции одной и той же программы для разных платформ. Conditional compilation is typically used to compile the same program for different platforms. Она также используется для предотвращения появления кода отладки в исполняемом файле. It is also used to prevent debugging code from appearing in an executable file. Код, исключаемый при условной компиляции, полностью удаляется из финального исполняемого файла, поэтому он не оказывает влияния на размер и производительность. Code excluded during conditional compilation is completely omitted from the final executable file, so it has no size or performance effect.
Независимо от результата любой оценки все выражения подвергаются оценке. Regardless of the outcome of any evaluation, all expressions are evaluated. Таким образом, все константы, используемые в выражении, должны быть определены — все неопределенные константы интерпретируется как пустые. Therefore, all constants used in expressions must be defined—any undefined constant evaluates as Empty.
Оператор **Option Compare ** не влияет на выражения операторов #If и #ElseIf. The Option Compare statement does not affect expressions in #If and #ElseIf statements. Выражения в директиве условного компилятора всегда вычисляются с помощью Option Compare Text. Expressions in a conditional-compiler directive are always evaluated with Option Compare Text.
Пример Example
Данный пример ссылается на константы условного компилятора в конструкции #If. Then. #Else конструкции, чтобы определить, следует ли выполнять компиляцию некоторых операторов. This example references conditional compiler constants in an #If. Then. #Else construct to determine whether to compile certain statements.
См. также See also
Поддержка и обратная связь Support and feedback
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Have questions or feedback about Office VBA or this documentation? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь. Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Использование операторов If. Then. Else Using If. Then. Else statements
Можно использовать оператор If. Then. Else для выполнения определенного оператора или блока операторов в зависимости от значения условия. You can use the If. Then. Else statement to run a specific statement or a block of statements, depending on the value of a condition. Операторы If. Then. Else могут быть вложены в любое необходимое число слоев. If. Then. Else statements can be nested to as many levels as you need.
Однако для удобства читаемости лучше использовать оператор Select Case вместо нескольких уровней вложенных операторов If. Then. Else. However, for readability, you may want to use a Select Case statement rather than multiple levels of nested If. Then. Else statements.
Выполнение операторов, если условие равно True Running statements if a condition is True
Чтобы выполнить только один оператор, когда условие равно True, используйте однострочный синтаксис оператора If. Then. Else. To run only one statement when a condition is True, use the single-line syntax of the If. Then. Else statement. В примере ниже показан однострочный синтаксис, пропускающий ключевое слово Else. The following example shows the single-line syntax, omitting the Else keyword.
Чтобы выполнить несколько строк кода, необходимо использовать многострочный синтаксис. To run more than one line of code, you must use the multiple-line syntax. Этот синтаксис включает оператор End If, как показано в примере ниже. This syntax includes the End If statement, as shown in the following example.
Выполнение определенных операторов, если условие равно True, и выполнение других операторов, если оно равно False Running certain statements if a condition is True and running others if it’s False
Используйте оператор If. Then. Else для определения двух блоков исполняемых операторов: один блок выполняется, если условие равно True, а другой блок выполняется, если условие равно False. Use an If. Then. Else statement to define two blocks of executable statements: one block runs if the condition is True, and the other block runs if the condition is False.
Проверка второго условия, если первое условие равно False Testing a second condition if the first condition is False
Можно добавить операторы ElseIf в оператор If. Then. Else для проверки второго условия, если первое условие равно False. You can add ElseIf statements to an If. Then. Else statement to test a second condition if the first condition is False. Например, в следующей процедуре функция вычисляет бонус на основе классификации задания. For example, the following function procedure computes a bonus based on job classification. Оператор, следующий за оператором Else, выполняется в том случае, если условия во всех операторах If и ElseIf равны False. The statement following the Else statement runs if the conditions in all of the If and ElseIf statements are False.
См. также See also
Поддержка и обратная связь Support and feedback
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Have questions or feedback about Office VBA or this documentation? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь. Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
if-else (Справочник по C#) if-else (C# Reference)
Оператор if определяет, какой оператор будет выполняться при выполнения условия, заданного логическим выражением. An if statement identifies which statement to run based on the value of a Boolean expression. В приведенном ниже примере переменной bool типа condition присваивается значение true , а затем она проверяется оператором if . In the following example, the bool variable condition is set to true and then checked in the if statement. В результате получается The variable is set to true. . The output is The variable is set to true. .
Примеры в этом разделе можно выполнить, разместив их в методе Main консольного приложения. You can run the examples in this topic by placing them in the Main method of a console app.
Оператор if в С# может иметь две формы, как показано в приведенном ниже примере. An if statement in C# can take two forms, as the following example shows.
В операторе if-else , если condition имеет значение true, выполняется then-statement . In an if-else statement, if condition evaluates to true, the then-statement runs. Если condition имеет значение false, выполняется else-statement . If condition is false, the else-statement runs. Так как condition не может одновременно иметь значения true и false, then-statement и else-statement оператора if-else не могут выполняться оба. Because condition can’t be simultaneously true and false, the then-statement and the else-statement of an if-else statement can never both run. После выполнения then-statement или else-statement управление передается следующему оператору после оператора if . After the then-statement or the else-statement runs, control is transferred to the next statement after the if statement.
В операторе if , не включающем оператор else , если condition имеет значение true, выполняется then-statement . In an if statement that doesn’t include an else statement, if condition is true, the then-statement runs. Если condition имеет значение false, то управление передается следующему оператору после оператора if . If condition is false, control is transferred to the next statement after the if statement.
then-statement и else-statement могут состоять из одного или нескольких операторов, заключенных в фигурные скобки ( <> ). Both the then-statement and the else-statement can consist of a single statement or multiple statements that are enclosed in braces ( <> ). Для одного оператора скобки необязательны, но рекомендуются. For a single statement, the braces are optional but recommended.
Оператор или операторы в then-statement и else-statement могут быть любого типа, включая другой оператор if , вложенный в исходный оператор if . The statement or statements in the then-statement and the else-statement can be of any kind, including another if statement nested inside the original if statement. Во вложенных операторах if каждое предложение else относится к последнему оператору if , у которого нет соответствующего объекта else . In nested if statements, each else clause belongs to the last if that doesn’t have a corresponding else . В приведенном ниже примере Result1 получается, если оба выражения m > 10 и n > 20 имеют значение true. In the following example, Result1 appears if both m > 10 and n > 20 evaluate to true. Если m > 10 имеет значение true, но n > 20 — значение false, то получается Result2 . If m > 10 is true but n > 20 is false, Result2 appears.
Если вместо этого нужно, чтобы Result2 получался, когда значение (m > 10) равно false, можно указать такую связь с помощью фигурных скобок для задания начала и конца вложенного оператора if , как показано в приведенном ниже примере. If, instead, you want Result2 to appear when (m > 10) is false, you can specify that association by using braces to establish the start and end of the nested if statement, as the following example shows.
Result2 получается, если условие (m > 10) имеет значение false. Result2 appears if the condition (m > 10) evaluates to false.
Пример Example
В приведенном ниже примере вы вводите символ с помощью клавиатуры, а программа использует вложенный оператор if для определения того, является ли введенный символ буквой. In the following example, you enter a character from the keyboard, and the program uses a nested if statement to determine whether the input character is an alphabetic character. Если введенный символ является буквой, программа определяет его регистр. If the input character is an alphabetic character, the program checks whether the input character is lowercase or uppercase. Для каждого случая предусмотрено отдельное сообщение. A message appears for each case.
Пример Example
Можно также поместить оператор if в блок else, как показано в части кода, приведенной ниже. You can also nest an if statement inside an else block, as the following partial code shows. В примере операторы if помещаются в два блока else и один блок then. The example nests if statements inside two else blocks and one then block. Комментарии определяют какие условия выполняются в каждом из блоков. The comments specify which conditions are true or false in each block.
Пример Example
В приведенном ниже примере определяется, является ли введенный символ строчной буквой, прописной буквой или цифрой. The following example determines whether an input character is a lowercase letter, an uppercase letter, or a number. Если все три условия имеют значение false, то символ не является алфавитно-цифровым. If all three conditions are false, the character isn’t an alphanumeric character. Для каждого случая выводится сообщение. The example displays a message for each case.
Точно так же как оператор в блоке else или блоке then может быть любым допустимым оператором, в качестве условия можно использовать любое допустимое логическое выражение. Just as a statement in the else block or the then block can be any valid statement, you can use any valid Boolean expression for the condition. Вы можете использовать логические операторы, такие как ! , && , || , & , | и ^ , для формирования составных условий. You can use logical operators such as ! , && , || , & , | , and ^ to make compound conditions. В коде ниже приведены примеры. The following code shows examples.
Спецификация языка C# C# language specification
Дополнительные сведения см. в спецификации языка C#. For more information, see the C# Language Specification. Спецификация языка является предписывающим источником информации о синтаксисе и использовании языка C#. The language specification is the definitive source for C# syntax and usage.