Excel VBA AND Function
VBA AND function checks the provided statement whether it is true or false. AND function also evaluates the conditions with one another. If both the statements are true, the expression becomes true. Commonly this is associated with different decision-making loops to express the conditions. Comparing to all other logical operators AND returns true only if all the supplied conditions are true.
When you want to evaluate more than one expression and take decisions according to that then logical operators are the best option. AND operators connect two or more conditions together and evaluate the entire statement as a single expression. If all the statement is true, then the total expression returns true. If any expression evaluates false, then the entire statement will return false.
How to Use the AND Function in Excel VBA?
The logical AND can be used along with comparison operators, arithmetic operators, and text, etc. Any number of statements can be connected using AND. The logic behind AND operator is as follows.
Condition 1 | Condition 2 | Result |
TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE |
FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE |
When more than two conditions are used, each condition should return true to make the entire expression true.
Syntax of VBA AND:
Format of VBA AND is expressed as,
[Condition1] And [Condition 2] And [Condition 3] And………. [Condition n]
- [Condition 1 to Condition n] can be a statement expressed using text and any operators.
You can download this VBA AND Excel Template here – VBA AND Excel Template
Example #1
In this example, you can learn how to use AND function along with comparison operators. You have the marks scored by a student in a different subject. If the total comes more than 80 and 22 marks on the main subject the student got passed in the exam else fail. For this, follow the below steps:
Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.
Step 2: Create a function named result in VBA to do the calculation and find the total mark of all subjects.
Code:
Private Sub result() End Sub
Step 3: Give the marks for different subjects. a, b, c, d are different subjects and the marks scored for each subject is as below. a is the main subject and s is the sum of all subjects a, b, c, d.
Code:
Private Sub result() a = 25 b = 20 c = 20 d = 20 s = a + b + c + d End Sub
Step 4: Now express the conditions as two statements and connect with AND function. IF …Else loop is used to execute the two different results according to the evaluation of the expression.
Code:
Private Sub result() a = 25 b = 20 c = 20 d = 20 s = a + b + c + d If s > 80 And a > 22 Then Else End If End Sub
Step 5: Set the message to show according to the condition valuation. Where both conditions are true the entire expression becomes true and the true section of IF… Else loop will execute. Else the control will move to the false section.
Code:
Private Sub result() a = 25 b = 20 c = 20 d = 20 s = a + b + c + d If s > 80 And a > 22 Then MsgBox "Student got passed the exam" Else MsgBox "Failed" End If End Sub
So if the sum is greater than 80 and the mark for the main subject ‘a’ is greater than 22 then the message “student got passed the exam” will show else fail is the result.
Step 6: Run this code by hitting the F5 or Run button which is placed on the topmost ribbon of VBE. The marks scored in the main subject is greater than 22 and the sum of all subject is greater than 80.
Here both the condition is true so the entire logical AND expression become true and the message in true section of IF… Else loop will be executed.
Example #2
There is no limit for giving the number of conditions with VBA AND. You can use ‘n’ number of conditions and VBA AND operator within a single expression. From an employee database, you have the attendance of a particular employee. You have the number of days that he was present in the office for the past 5 months. If the employee has 25 or more than 25 days’ attendance for every month, he is eligible for a bonus. For this, follow the below steps:
Step 1: In the same module let us start with another subprocedure.
Code:
Private Sub bonus() End Sub
Step 2: To check the above conditions, start with a function ‘bonus’ and attendance for each month.
Private Sub bonus() jan = 25 feb = 24 mar = 25 apr = 25 End Sub
Step 3: Now, check each month’s attendance to confirm whether it is greater than or equal to 25. So multiple ‘AND’ operators are used to check the condition. The value of the entire expression is assigned to ‘b’ which returns a Boolean value.
Code:
Private Sub bonus() jan = 25 feb = 24 mar = 25 apr = 25 b = jan >= 25 And feb >= 25 And mar >= 25 And apr >= 25 End Sub
Step 4: According to this Boolean value, you can a loop. The value of ‘b’ should be true or false.
Code:
Private Sub bonus() jan = 25 feb = 24 mar = 25 apr = 25 b = jan >= 25 And feb >= 25 And mar >= 25 And apr >= 25 If b = "True" Then MsgBox " Employee eligible for bonus" End If If b = "False" Then MsgBox "Employee does not meet the criteria" End If End Sub
Two IF loops are set to execute according to the Boolean value of b. Here apart from Feb all month’s attendance is greater than or equal to 25. But even a single statement evaluates false the entire expression becomes false. ‘AND’ function returns false and the value of ‘b’ becomes false.
Step 5: So the second IF loop will be executed and the message within this will display as “Employee does not meet the criteria.
Here expression is evaluated as follows. First and last two conditions are true and the second condition is false. So while evaluating the entire expression, it becomes false.
Example #3
VBA AND to Evaluate User Credentials. Create a sign-in form using forms and controls in VBA which is available in the code window. For this, follow the below steps:
Step 1: Now Insert a new UserForm inside Visual Basic Editor (VBE). Click on Insert tab > select UserForm. Design a window using Toolbox with a user name, password and a sign-in button.
Step 2: Click the Sign-in button using the AND operator. Once the credentials are provided check the text value comes to both username and password textboxes, Textbox1 and Textbox 2. If the username is “Tutorial” and password is “Edcba1A45” then the credentials are correct and the user will be able to sign in and a welcome message will be displayed. Else error message is displayed.
Code:
Private Sub CommandButton1_Click() If (TextBox1.Text = "Tutorial") And (TextBox2.Text = "Edcba1A45") Then MsgBox "Welcome to your account'" Else MsgBox "Oops username or password is incorrect" End If End Sub
Step 3: Both conditions are expressed in an IF loop. AND operator evaluates these both conditions. Run the form using the run button and give username and password in the text field.
Since the username is “Tutorial” and password is “Edcba1A45” the AND operator returns a true and true block of IF loop will execute.
Things to Remember
- The logical AND function will always return a Boolean value true or false
- Commonly use with decision-making loops.
- Helps to compare ‘n’ number of expressions at a time by connecting with logical AND
- The entire statement returns true only if each statement is true.
Recommended Articles
This is a guide to the VBA AND. Here we discuss how to Use the AND Function in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA PasteSpecial
- VBA Dynamic Array
- VBA ReDim Array
- VBA SubString
This Excel tutorial explains how to use the Excel AND function (in VBA) with syntax and examples.
Description
The Microsoft Excel AND function returns TRUE if all conditions are TRUE. It returns FALSE if any of the conditions are FALSE.
The AND function is a built-in function in Excel that is categorized as a Logical Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.
Please read our AND function (WS) page if you are looking for the worksheet version of the AND function as it has a very different syntax.
Syntax
The syntax for the AND function in Microsoft Excel is:
condition1 And condition2 [... And condition_n]
Parameters or Arguments
- condition1, condition2, … condition_n
- Expressions that you want to test that can either be TRUE or FALSE.
Returns
The AND function returns TRUE if all conditions are TRUE.
The AND function returns FALSE if any of the conditions are FALSE.
Applies To
- Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Type of Function
- VBA function (VBA)
Example (as VBA Function)
Let’s look at some Excel AND function examples and explore how to use the AND function in Excel VBA code.
This first example combines the AND function with the IF Statement in VBA code:
If LWebsite = "TechOnTheNet.com" And LPages <= 10 Then LBandwidth = "Low" Else LBandwidth = "High" End If
This would set the LBandwidth variable to the string value «Low» if both LWebsite was «TechOnTheNet.com» and LPages <= 10. Otherwise, it would set the LBandwidth variable to the string value «High».
This second example uses the AND function with the OR function in VBA, for example:
If (LWebsite = "TechOnTheNet.com" Or LWebsite = "CheckYourMath.com") And LPages <= 10 Then LBandwidth = "Low" Else LBandwidth = "High" End If
This would set the LBandwidth variable to the string value «Low» if LWebsite was either «TechOnTheNet.com» or «CheckYourMath.com» and LPages <= 10. Otherwise, it would set the LBandwidth variable to the string value «High».
AND function is a logical function as well as a logical operator. We can have the “TRUE” result if all the conditions are fulfilled in this function. If any of the conditions fails, the output returns “FALSE.” We have a built-in AND command in VBA to use.
We hope you have reviewed our articles on “VBA OROr is a logical function in programming languages, and we have an OR function in VBA. The result given by this function is either true or false. It is used for two or many conditions together and provides true result when either of the conditions is returned true.read more” and “VBA IF ORIF OR is not a single statement; it is a pair of logical functions used together in VBA when we have more than one criteria to check, and when we use the if statement, we receive the true result if either of the criteria is met.read more.” This function is just the opposite of the OR function. In the OR function, to get the result as “TRUE,” we need any of the supplied logical conditions to be satisfied. But in the AND function, it is just the reverse. To get the “TRUE” result, all the supplied logical tests in excelA logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test.read more must be satisfied.
Look at the syntax of the AND function in excelThe AND function in Excel is classified as a logical function; it returns TRUE if the specified conditions are met, otherwise it returns FALSE.read more.
Table of contents
- Excel VBA AND Function
- Examples to Use VBA And Function
- Example #1
- Example #2
- Example #3
- Recommended Articles
- Examples to Use VBA And Function
[Logical Test] AND [Logical Test] AND [Logical Test]
In the above, we have two test scores out of 600.
In the result column, we need to get the result as “TRUE” if the score of both the tests is greater than equal to 250.
For example, look at the below image.
When we applied the logical function AND, we got the results. For example, in cells C4 and C5, we got the result as “TRUE” because Test 1 and Test 2 scores are greater than or equal to 250.
Look at the C6 cell here. We have got “FALSE” even though the score of Test 2 equals 250 because, in Test 1, the score is only 179.
Examples to Use VBA And Function
You can download this VBA AND Excel Template here – VBA AND Excel Template
Example #1
For example, we will test the numbers here, whether 25>=20 and 30<=31.
Step 1: Declare the variable as String.
Code:
Sub AND_Example1() Dim K As String End Sub
Step 2: For the variable “k,” we will assign the value by applying the AND function.
Code:
Sub AND_Example1() Dim K As String K = End Sub
Step 3: Supply the first condition as 25>=20.
Code:
Sub AND_Example1() Dim K As String K = 25 >= 20 End Sub
Step 4: Now, open AND function and supply the second logical test, 30<=29.
Code:
Sub AND_Example1() Dim K As String K = 25 >= 20 And 30 <= 29 End Sub
Step 5: Now, show the variable “k” result in the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.
Code:
Sub AND_Example1() Dim K As String K = 25 >= 20 And 30 <= 29 MsgBox K End Sub
Run the macro to see what the result is.
We got the result as “FALSE” because we applied two conditions. The first condition 25>=20, this condition is satisfied, so the result is “TRUE.” However, the second condition, 30<=29, is not satisfied, so the result is “FALSE.” To get the result as TRUE, both the conditions should be satisfied.
Example #2
Now, we will change the logical test to “100>95 AND 100<200.”
Code:
Sub AND_Example2() Dim k As String k = 100 > 95 And 100 < 200 MsgBox k End Sub
Run the code to see the result.
Here, we got “TRUE” as a result because:
1st Logical Test: 100 > 95 = TRUE
2nd Logical Test: 100 < 200 = TRUE
Our final result is “TRUE” since we got the “TRUE” results for both the logical tests.
Example #3
Now, we will see data from the worksheet. First, use the data we have used to show the example of the Excel AND function.
Here the condition is Test 1 Score >= 250 AND Test 2 Score >= 250.
Since we have more than one data cell, we need to use loops to avoid writing unnecessary and time-consuming lines of code. So, we have written the code below for you. The formula and logic are the same because we have only used “VBA For Next LoopAll programming languages make use of the VBA For Next loop. After the FOR statement, there is a criterion in this loop, and the code loops until the criteria are reached. read more.”
Code:
Sub AND_Example3() Dim k As Integer For k = 2 To 6 Cells(k, 3).Value = Cells(k, 1) >= 250 And Cells(k, 2) >= 250 Next k End Sub
It will give the same result as our worksheet function, but we will not get any formulas. We get only results.
Like this, we can apply the AND logical function to test multiple conditions, which should all be “TRUE” to arrive at the desired results.
It works opposite the OR function, where OR requires any supplied conditions to be “TRUE” to arrive at the results. But, AND function requires 100% result in a logical test to arrive at the results.
Recommended Articles
This article is a guide to VBA AND Function. Here, we learn how to use AND logical operator with practical examples and download an Excel template. You may also have a look at other articles related to Excel VBA: –
- Application.Match in VBA
- VBA Wait
- VBA DatePart
- Data Types in VBA
Операторы, использующиеся в VBA Excel для отрицания и сравнения логических выражений. Синтаксис, принимаемые значения, приоритет логических операторов.
Оператор «Not»
«Not» – это оператор логического отрицания (инверсия), который возвращает True, если условие является ложным, и, наоборот, возвращает False, если условие является истинным.
Синтаксис:
Таблица значений:
Условие | Результат |
---|---|
True | False |
False | True |
Оператор «And»
«And» – это оператор логического умножения (логическое И, конъюнкция), который возвращает значение True, если оба условия являются истинными.
Синтаксис:
Результат = Условие1 And Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Оператор «Or»
«Or» – это оператор логического сложения (логическое ИЛИ, дизъюнкция), который возвращает значение True, если одно из двух условий является истинным, или оба условия являются истинными.
Синтаксис:
Результат = Условие1 Or Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
Оператор «Xor»
«Xor» – это оператор логического исключения (исключающая дизъюнкция), который возвращает значение True, если только одно из двух условий является истинным.
Синтаксис:
Результат = Условие1 Xor Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | False |
True | False | True |
False | True | True |
False | False | False |
Оператор «Eqv»
«Eqv» – это оператор логической эквивалентности (тождество, равенство), который возвращает True, если оба условия имеют одинаковое значение.
Синтаксис:
Результат = Условие1 Eqv Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | True |
Оператор «Imp»
«Imp» – это оператор логической импликации, который возвращает значение False, если первое (левое) условие является истинным, а второе (правое) условие является ложным, в остальных случаях возвращает True.
Синтаксис:
Результат = Условие1 Imp Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | True |
True | False | False |
False | True | True |
False | False | True |
Приоритет логических операторов
Приоритет определяет очередность выполнения операторов в одном выражении. Очередность выполнения логических операторов в VBA Excel следующая:
- «Not» – логическое отрицание;
- «And» – логическое И;
- «Or» – логическое ИЛИ;
- «Xor» – логическое исключение;
- «Eqv» – логическая эквивалентность;
- «Imp» – логическая импликация.
VBA AND function in Excel is categorized as a logical function in VBA. It is a built-in function in MS Office Excel VBA. This function returns true, if all the conditions are TRUE. This function is used to combine more than one condition with using ‘AND’ keyword. This is one of the most used logical operator. It has minimum two conditional input parameters. It returns a Boolean value either True or False.
We can use this function as a worksheet function and also use in VBA. This function use in either procedure or function in a VBA editor window in Excel. We can use this VBA AND function any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the AND function, where we can use this VBA AND function and real-time examples.
Table of Contents:
- Overview
- Syntax of VBA AND Function
- Parameters or Arguments
- Where we can apply or use VBA AND Function?
- Example 1: Check two conditions are true or not(TRUE)
- Example 2: Check two conditions are true or not(FALSE)
- Example 3: Check two conditions are true or not(TRUE)
- Instructions to Run VBA Macro Code
- Other Useful Resources
The syntax of the VBA AND function is
Condition1 AND Condition2 'or Condition1 AND Condition2 [...AND ConditionN]
The VBA AND function returns Boolean value either True or False. It returns TRUE, if all conditions are TRUE. Otherwise returns FALSE.
Parameters or Arguments
The AND function has one input parameter or argument.
Where
Condition1 & Condition2: Both are required parameters. Here we evaluate specified all conditions are true or not.
Where we can apply or use VBA AND Function?
We can use this VBA AND function in MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.
Example 1: Check two conditions are true or not(TRUE)
Here is a simple example of the VBA AND function. This below example macro checks two specified conditions. The output of below macro is TRUE.
'Check two conditions are true or not Sub VBA_AND_Function_Ex1() If (A = A) And (1 = 1) Then MsgBox "Specified conditions are : TRUE ", vbInformation, "VBA AND Function" Else MsgBox "Specified conditions are : FALSE ", vbInformation, "VBA AND Function" End If End Sub
Output: Here is the screen shot of the first example output.
Example 2: Check two conditions are true or not(FALSE)
Here is a another example of the VBA AND function. This below example code checks two specified conditions. The output of below macro is FALSE.
'Check two conditions are true or not Sub VBA_AND_Function_Ex2() If (A = A) And (1 = 2) Then MsgBox "Specified conditions are : TRUE ", vbInformation, "VBA AND Function" Else MsgBox "Specified conditions are : FALSE ", vbInformation, "VBA AND Function" End If End Sub
Output: Here is the screen shot of the second example output.
Example 3: Check two conditions are true or not(TRUE)
Here is a simple example of the VBA AND function. This below example macro checks three specified conditions. The output of below macro is TRUE.
'Check more than two conditions are true or not Sub VBA_AND_Function_Ex3() If (A = A) And (1 = 1) And (Z = Z) Then MsgBox "Specified conditions are : TRUE ", vbInformation, "VBA AND Function" Else MsgBox "Specified conditions are : FALSE ", vbInformation, "VBA AND Function" End If End Sub
Output:Here is the screen shot of the third example output.
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays in Excel Blog
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers
In this Article
- Using the And Logical Operator
- Using the Or Logical Operator
- Using the Not Logical Operator
- Using the Xor Logical Operator
- Is Operator
- Like Operator
VBA allows you to use the logical operators And, Or, Not, Xor to compare values. The operators are considered “Boolean”, which means they return True or False as a result.
If you want to learn how to compare strings, click here: VBA Compare Strings – StrComp
If you want to learn how to use comparison operators, click here: VBA Comparison Operators – Not Equal to & More
Using the And Logical Operator
The And logical operator compares two or more conditions. If all the conditions are true, the operator will return True. If at least one of the conditions is not true, the operator will return False. Here is an example:
Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
intA = 5
intB = 5
If intA = 5 And intB = 5 Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if both intA and intB are equal to 5. If this is true, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set values of intA and intB to 5:
intA = 5
intB = 5
After that, we use the And operator in the If statement to check if the values are equal to 5:
If intA = 5 And intB = 5 Then
blnResult = True
Else
blnResult = False
End If
As both variables are equal to 5, the blnResult returns True:
Image 1. Using the And logical operator in VBA
Using the Or Logical Operator
The Or logical operator compares two or more conditions. If at least one of the conditions is true, it will return True. If none of the conditions are true, the operator will return False. Here is the code for the example:
Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
intA = 5
intB = 10
If intA = 5 Or intB = 5 Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if both intA is equal to 5. or intB is equal to 10. If any of these conditions is true, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set the value of intA to 5 and intB to 10:
intA = 5
intB = 10
After that, we use the Or operator in the If statement to check if any of the values is equal to 5:
If intA = 5 Or intB = 5 Then
blnResult = True
Else
blnResult = False
End If
As intA value is 5, the blnResult returns True:
Image 2. Using the Or logical operator in VBA
Using the Not Logical Operator
The Not logical operator checks one or more conditions. If the conditions are true, the operator returns False. Otherwise, it returns True. Here is the code for the example:
Dim intA As Integer
Dim blnResult As Boolean
intA = 5
If Not (intA = 6) Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if the value of intA is not equal to 6. If intA is different than 6, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set the value of intA to 5:
intA = 5
After that, we use the Not operator in the If statement to check if the value of intA is different than 6:
If Not (intA = 6) Then
blnResult = True
Else
blnResult = False
End If
As intA value is 5, the blnResult returns True:
Image 3. Using the Not logical operator in VBA
Using the Xor Logical Operator
The Xor logical operator compares two or more conditions. If exactly one of the conditions is true, it will return True. If none of the conditions are true, or more than one are true, it will return False. Here is the code for the example:
Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
intA = 5
intB = 10
If intA = 5 Xor intB = 5 Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if exactly one of the values (intA or IntB) are equal to 5. If only one condition is true, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set the value of intA to 5 and intB to 10:
intA = 5
intB = 10
After that, we use the Or operator in the If statement to check if any of the values is equal to 5:
If intA = 5 Xor intB = 5 Then
blnResult = True
Else
blnResult = False
End If
As intA value is 5 and intB is 10, the blnResult returns True:
Image 4. Using the Xor logical operator in VBA
Is Operator
The Is Operator tests if two object variables store the same object.
Let’s look at an example. Here we will assign two worksheets to worksheet objects rng1 and rng2, testing if the two worksheet objects store the same worksheet:
Sub CompareObjects()
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
If ws1 Is ws2 Then
MsgBox "Same WS"
Else
MsgBox "Different WSs"
End If
End Sub
Of course the worksheet objects are not the same, so “Different WSs” is returned.
Like Operator
The Like Operator can compare two strings for inexact matches. This example will test if a string starts with “Mr.”
Sub LikeDemo()
Dim strName As String
Dim blnResult As Boolean
strName = "Mr. Michael James"
If strName Like "Mr*" Then
blnResult = True
Else
blnResult = False
End If
End Sub
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
AlexBosenko Пользователь Сообщений: 195 |
#1 11.08.2017 09:57:37 Добрый день. Помогите понять, почему может не работать следующий макрос? Какие параметры функции AND или как написать по другому? Спасибо.
Изменено: AlexBosenko — 11.08.2017 09:58:07 |
||
kuklp Пользователь Сообщений: 14868 E-mail и реквизиты в профиле. |
#2 11.08.2017 10:05:09 Не знаю, как модеры отнесутся к названию темы. И мой Вам совет, описывайте свою задачу(с примером, как положено), а не Ваше видение ее решения. Правила почитать. Зачем темам давать осмысленное название? предложите новое название темы. Модераторы исправят. Пока тему не закрыли. А по теме предположительно And вообще ни к чему.
или так:
Изменено: kuklp — 12.08.2017 10:32:08 Я сам — дурнее всякого примера! … |
||||
Equio Пользователь Сообщений: 274 |
#3 12.08.2017 09:34:36 Функция «And» в VBA (как, кстати, и в других языках программирования) применяется, когда требуется проверка одновременного выполнения двух или более условий. Она НЕ применяется для записи в одну строку нескольких команд. Команды в VBA записываются либо одна под другой, либо в одну строку через двоеточие.
Т.е. если Вы хотите перевести с человеческого языка на язык VBA такую конструкцию «если выполняется условие1, то выполнить действие1 и выполнить действие2», то несмотря на то, что в человеческом языке команды «выполнить действие1», «выполнить действие2» соединяются с помощью «и», на языке VBA в этом случае «and» не используется, эти две команды на выполнение действий либо записываются в двух разных строчках одна под другой, либо в одну строчку с двоеточием между ними. А если мы переводим с человеческого языка на язык VBA конструкцию «если одновременно выполняются условие1 и условие2, то выполнить действие1», то на языке VBA условие1 и условие2 записываются в одну строчку и между ними ставится «And». Изменено: Equio — 12.08.2017 09:58:58 |
||
ZVI Пользователь Сообщений: 4328 |
#4 12.08.2017 11:34:43
Иногда все же применяется для побитовых (бинарных) операций: 2 Or 4, 5 And 3 , даже Not 2 , подробнее здесь . Но по данной теме все правильно написано Изменено: ZVI — 12.08.2017 11:36:06 |
||
Использование and мне в данном случае напоминает &/&& в shell скриптах. Такое ощущение, что ТС захотел получить такой же эффект как описано вот в этой статье (на английском правда) https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true В привычном (для shell-скриптинга) понимании этого способа использование and в vba в указанном виде я не вижу. Если хочется все уместить в одну строку, обычно выражения отделяют двоеточием. Где-то читал, что это может несущественно сократить время работы макроса. С уважением, |
|
ZVI Пользователь Сообщений: 4328 |
Если бы продавцом был VBA, то он мог бы коварно спросить у покупателя: «Сколько взвесить арбузов и дынь?» и на ответ «5 и 3» взвесил бы 1 не знаю даже чего Изменено: ZVI — 12.08.2017 13:16:20 |
Equio Пользователь Сообщений: 274 |
ZVI, спасибо за интересное дополнение. Вам приходилось это использовать в решении какой-нибудь практической задачи? |
vikttur Пользователь Сообщений: 47199 |
|
kuklp Пользователь Сообщений: 14868 E-mail и реквизиты в профиле. |
#9 12.08.2017 14:48:34
Я сам — дурнее всякого примера! … |
||||
Equio Пользователь Сообщений: 274 |
#10 12.08.2017 15:13:29
Ради интереса потестировал. В простейшем случае скорость одинаковая. Такой код
даёт такое же время расчёта, как и без двоеточия в две строки. |
||||
ZVI Пользователь Сообщений: 4328 |
#11 12.08.2017 15:27:37
|
||||
Equio Пользователь Сообщений: 274 |
#12 12.08.2017 16:41:31 ZVI, спасибо. Есть ли какие-то преимущества перед просто проверкой на Not(arr) = -1? Изменено: Equio — 12.08.2017 16:55:07 |
Home / VBA / VBA IF And (Test Multiple Conditions)
You can use the AND operator with the VBA IF statement to test multiple conditions, and when you use it allows you to test two conditions simultaneously and get true if both of those conditions are true. And, if any of the conditions is false it returns false in the result.
Combining IF AND
- First, start the IF statement with the “IF” keyword.
- After that, specify the first condition that you want to test.
- Next, use the AND keyword to specify the second condition
- In the end, specify the second condition that you want to test.
To have a better understanding let’s see an example.
Sub myMacro()
If 1 = 1 And 2 > 1 Then
MsgBox "Both of the conditions are true."
Else
MsgBox "Maybe one or both of the conditions are true."
End If
End Sub
If you look at the above example, we have specified two conditions one if (1 = 1) and the second is (2 > 1) and here both of the conditions are true, and that’s why it has executes the line of code that we have specified if the result is true.
Now lets if one of these two conditions is false, let me use the different code here.
Sub myMacro1()
If 1 = 1 And 2 < 1 Then
MsgBox "Both of the conditions are true."
Else
MsgBox "Maybe one or both of the conditions are true."
End If
End Sub
In the above code, the second condition is false (2 < 1) and when you run this macro it executes the line of code that we have specified if the result is false.
In the same way, you can also test more than two conditions at the same time. Let’s continue the above example and add the third condition to it.
Sub myMacro2()
If 1 = 1 And 2 > 1 And 1 - 1 = 0 Then
MsgBox "All the conditions are true."
Else
MsgBox "Some conditions are false."
End If
End Sub
Now we have three conditions to test and we have used the AND after the second condition to specify the third condition. As you learned above that when you use AND, all the conditions need to be true to get true in the result.
When you run this code, it executes the line of code that we have specified for the true.
And if any of the conditions is false, just like you have in the following code, it returns false.
Sub myMacro3()
If 1 = 1 And 2 < 1 And 1 + 1 = 0 Then
MsgBox "All the conditions are true."
Else
MsgBox "Some conditions are false."
End If
End Sub