- Использование операторов If. Then. Else
- Выполнение операторов, если условие равно True
- Выполнение определенных операторов, если условие равно True, и выполнение других операторов, если оно равно False
- Проверка второго условия, если первое условие равно False
- См. также
- Поддержка и обратная связь
- Обратная связь
- Using If. Then. Else statements
- Running statements if a condition is True
- Running certain statements if a condition is True and running others if it's False
- Testing a second condition if the first condition is False
- See also
- Support and feedback
- If. Then. Else statement
- Syntax
- Remarks
- Example
- See also
- Support and feedback
Использование операторов If. Then. Else
Используйте оператор If. Then. Else для выполнения определенного оператора или блока операторов в зависимости от значения условия. Операторы If. Then. Else могут быть вложены в любое необходимое число слоев.
Однако для удобства читаемости лучше использовать оператор Select Case вместо нескольких уровней вложенных операторов If. Then. Else.
Выполнение операторов, если условие равно True
Чтобы выполнить только один оператор, когда условие равно True, используйте однострочный синтаксис оператора If. Then. Else. В следующем примере показан однострочный синтаксис с ключевым словомElse.
Sub FixDate() myDate = #2/13/95# If myDate < Now Then myDate = Now End Sub
Чтобы выполнить несколько строк кода, необходимо использовать многострочный синтаксис. Этот синтаксис включает оператор End If, как показано в примере ниже.
Sub AlertUser(value as Long) If value = 0 Then AlertLabel.ForeColor = "Red" AlertLabel.Font.Bold = True AlertLabel.Font.Italic = True End If End Sub
Выполнение определенных операторов, если условие равно True, и выполнение других операторов, если оно равно False
Используйте оператор If. Then. Else для определения двух блоков исполняемых операторов: один блок выполняется, если условие равно True, а другой блок выполняется, если условие равно False.
Sub AlertUser(value as Long) If value = 0 Then AlertLabel.ForeColor = vbRed AlertLabel.Font.Bold = True AlertLabel.Font.Italic = True Else AlertLabel.Forecolor = vbBlack AlertLabel.Font.Bold = False AlertLabel.Font.Italic = False End If End Sub
Проверка второго условия, если первое условие равно False
Можно добавить операторы ElseIf в оператор If. Then. Else для проверки второго условия, если первое условие равно False. Например, в следующей процедуре функция вычисляет бонус на основе классификации задания. Оператор, следующий за оператором Else, выполняется в том случае, если условия во всех операторах If и ElseIf равны False.
Function Bonus(performance, salary) If performance = 1 Then Bonus = salary * 0.1 ElseIf performance = 2 Then Bonus = salary * 0.09 ElseIf performance = 3 Then Bonus = salary * 0.07 Else Bonus = 0 End If End Function
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Обратная связь
Были ли сведения на этой странице полезными?
Using If. Then. Else statements
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 statements can be nested to as many levels as you need.
However, for readability, you may want to use a Select Case statement rather than multiple levels of nested If. Then. Else statements.
Running statements if a condition is True
To run only one statement when a condition is True, use the single-line syntax of the If. Then. Else statement. The following example shows the single-line syntax, omitting the Else keyword.
Sub FixDate() myDate = #2/13/95# If myDate < Now Then myDate = Now End Sub
To run more than one line of code, you must use the multiple-line syntax. This syntax includes the End If statement, as shown in the following example.
Sub AlertUser(value as Long) If value = 0 Then AlertLabel.ForeColor = "Red" AlertLabel.Font.Bold = True AlertLabel.Font.Italic = True End If End Sub
Running certain statements if a condition is True and running others if it's 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.
Sub AlertUser(value as Long) If value = 0 Then AlertLabel.ForeColor = vbRed AlertLabel.Font.Bold = True AlertLabel.Font.Italic = True Else AlertLabel.Forecolor = vbBlack AlertLabel.Font.Bold = False AlertLabel.Font.Italic = False End If End Sub
Testing a second condition if the first condition is 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. The statement following the Else statement runs if the conditions in all of the If and ElseIf statements are False.
Function Bonus(performance, salary) If performance = 1 Then Bonus = salary * 0.1 ElseIf performance = 2 Then Bonus = salary * 0.09 ElseIf performance = 3 Then Bonus = salary * 0.07 Else Bonus = 0 End If End Function
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
If. Then. Else statement
Conditionally executes a group of statements, depending on the value of an expression.
Syntax
If condition Then [ statements ] [ Else elsestatements ]
Or, you can use the block form syntax:
If condition Then
[ statements ]
[ ElseIf condition-n Then
[ elseifstatements ]]
[ Else
[ elsestatements ]]
End If
The If. Then. Else statement syntax has these parts.
A numeric expression or string expression that evaluates to True or False. If condition is Null, condition is treated as False.
Remarks
Use the single-line form (first syntax) for short, simple tests. However, the block form (second syntax) provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug.
With the single-line form, it is possible to have multiple statements executed as the result of an If. Then decision. All statements must be on the same line and separated by colons, as in the following statement:
If A > 10 Then A = A + 1 : B = B + A : C = C + B
A block form If statement must be the first statement on a line. The Else, ElseIf, and End If parts of the statement can have only a line number or line label preceding them. The block If must end with an End If statement.
To determine whether or not a statement is a block If, examine what follows the Then keyword. If anything other than a comment appears after Then on the same line, the statement is treated as a single-line If statement.
The Else and ElseIf clauses are both optional. You can have as many ElseIf clauses as you want in a block If, but none can appear after an Else clause. Block If statements can be nested; that is, contained within one another.
When executing a block If (second syntax), condition is tested. If condition is True, the statements following Then are executed. If condition is False, each ElseIf condition (if any) is evaluated in turn. When a True condition is found, the statements immediately following the associated Then are executed. If none of the ElseIf conditions are True (or if there are no ElseIf clauses), the statements following Else are executed. After executing the statements following Then or Else, execution continues with the statement following End If.
Select Case may be more useful when evaluating a single expression that has several possible actions. However, the TypeOf objectname Is objecttype clause can't be used with the Select Case statement.
TypeOf cannot be used with hard data types such as Long, Integer, and so forth other than Object.
Example
This example shows both the block and single-line forms of the If. Then. Else statement. It also illustrates the use of If TypeOf. Then. Else.
Dim Number, Digits, MyString Number = 53 ' Initialize variable. If Number < 10 Then Digits = 1 ElseIf Number < 100 Then ' Condition evaluates to True so the next statement is executed. Digits = 2 Else Digits = 3 End If ' Assign a value using the single-line form of syntax. If Digits = 1 Then MyString = "One" Else MyString = "More than one"
Use the If TypeOf construct to determine whether the Control passed into a procedure is a text box.
Sub ControlProcessor(MyControl As Control) If TypeOf MyControl Is CommandButton Then Debug.Print "You passed in a " & TypeName(MyControl) ElseIf TypeOf MyControl Is CheckBox Then Debug.Print "You passed in a " & TypeName(MyControl) ElseIf TypeOf MyControl Is TextBox Then Debug.Print "You passed in a " & TypeName(MyControl) End If End Sub
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.