Функция and миф excel

VBA AND

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.

Insert 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

VBA AND Example1-2

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

VBA AND Example1-3

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

VBA AND Example1-4

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

IF-Else loop Example1-5

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.

VBA AND Example1-6

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

VBA AND Example2-1

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

VBA AND Example2-2

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

VBA AND Example2-3

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

Loop Example2-4

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.

VBA AND Example2-5

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.

UserForm Example3-1

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

VBA AND Example3-2

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.

User Credentials Example3-3

User Credentials3-3

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 –

  1. VBA PasteSpecial
  2. VBA Dynamic Array
  3. VBA ReDim Array
  4. VBA SubString

totn Excel Functions


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».

Операторы, использующиеся в 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 следующая:

  1. «Not» – логическое отрицание;
  2. «And» – логическое И;
  3. «Or» – логическое ИЛИ;
  4. «Xor» – логическое исключение;
  5. «Eqv» – логическая эквивалентность;
  6. «Imp» – логическая импликация.

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
[Logical Test] AND [Logical Test] AND [Logical Test]

AND function 1

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.

AND function 1-1

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

VBA AND Example 1-3

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

VBA AND Example 1-2

Step 3: Supply the first condition as 25>=20.

Code:

Sub AND_Example1()

  Dim K As String

  K = 25 >= 20

End Sub

Example 1-4

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

Example 1-5

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

Example 1-6

Run the macro to see what the result is.

VBA AND Example 1-7

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.

VBA AND Example 2

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.

Example 3

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.

VBA AND Example 3-1

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 Logical Operators: AND, OR, NOT

Let’s say you want to process a customer order. For that, you want to first check to see if the ordered product exists or not. If it does, you also want to check if the quantity on hand is enough. Logical operators come in handy in such cases. Logical operators are used to evaluate more than one condition.

The main Excel VBA logical operators AND, OR, NOT are listed in the table below:

S/N Operator Description Example Output
1 AND AND: This is used to combine more than one condition. If all the conditions are true, AND evaluates to true. If any of the condition is false, AND evaluates to false If true = true AND false = true THEN false
2 OR OR: This is used to combine more than one condition. If any of the conditions evaluate to true, OR returns true. If all of them are false, OR returns false If true = true OR true = false THEN true
3 NOT NOT: This one works like an inverse function. If the condition is true, it returns false, and if a condition is false, it returns true. If NOT (true) Then false

VBA Logical Operators Example Source Code

For the sake of simplicity, we will be comparing hard coded numbers.

Add ActiveX buttons to the sheet from the “Insert option.”

Set the properties as shown in the image below

VBA Logical Operators

VBA Logical Operators

The following table shows the properties that you need to change and the values that you need to update too.

S/N Control Property Value
1 CommandButton1 Name btnAND
Caption AND Operator (0 = 0)
2 CommandButton2 Name btnOR
Caption OR Operator (1 = 1) Or (5 = 0)
3 CommandButton3 Name btnNOT
Caption NOT Operator Not (0 = )

Add the following code to btnAND_Click

Private Sub btnAND_Click()
    If (1 = 1) And (0 = 0) Then
            MsgBox "AND evaluated to TRUE", vbOKOnly, "AND operator"
        Else
            MsgBox "AND evaluated to FALSE", vbOKOnly, "AND operator"
    End If
End Sub

VBA If AND Operator

  • “If (1 = 1) And (0 = 0) Then” the if statement uses the AND logical operator to combine two conditions (1 = 1) And (0 = 0). If both conditions are true, the code above ‘Else’ keyword is executed. If both conditions are not true, the code below ‘Else’ keyword is executed.

Add the following code to btnOR_Click

Private Sub btnOR_Click()
    If (1 = 1) Or (5 = 0) Then
            MsgBox "OR evaluated to TRUE", vbOKOnly, "OR operator"
        Else
            MsgBox "OR evaluated to FALSE", vbOKOnly, "OR operator"
    End If
End Sub

VBA If OR Operator

  • “If (1 = 1) Or (5 = 0) Then” the if statement uses the OR logical operator to combine two conditions (1 = 1) And (5 = 0). If any of the conditions is true, the code above Else keyword is executed. If both conditions are false, the code below Else keyword is executed.

Add the following code to btnNOT_Click

Private Sub btnNOT_Click()
    If Not (0 = 0) Then
            MsgBox "NOT evaluated to TRUE", vbOKOnly, "NOT operator"
        Else
            MsgBox "NOT evaluated to FALSE", vbOKOnly, "NOT operator"
    End If
End Sub

VBA If NOT Operator

  • “If Not (0 = 0) Then” the VBA If Not function uses the NOT logical operator to negate the result of the if statement condition. If the conditions is true, the code below ‘Else’ keyword is executed. If the condition is true, the code above Else keyword is executed.

Download Excel containing above code

 

AlexBosenko

Пользователь

Сообщений: 195
Регистрация: 02.09.2016

#1

11.08.2017 09:57:37

Добрый день. Помогите понять, почему может не работать следующий макрос? Какие параметры функции AND или как написать по другому? Спасибо.  

Код
If ComboBox1 = "Pre-payment" Then
         Cells(6, 2) = "  V  " And Cells(6, 11) = Empty
      Else
        Cells(6, 11) = "  V  " And Cells(6, 2) = Empty
      End If

Изменено: AlexBosenko11.08.2017 09:58:07

 

kuklp

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

#2

11.08.2017 10:05:09

Не знаю, как модеры отнесутся к названию темы. И мой Вам совет, описывайте свою задачу(с примером, как положено), а не Ваше видение ее решения.
Еще Вам бы

Правила

почитать.

Зачем темам давать осмысленное название?

предложите новое название темы. Модераторы исправят.  Пока тему не закрыли. А по теме предположительно And вообще ни к чему.

Код
If ComboBox1 = "Pre-payment" Then
 Cells(6, 2) = " V " 
Cells(6, 11) = Empty
 Else
 Cells(6, 11) = " V " 
Cells(6, 2) = Empty
end if

или так:

Код
Cells(6, 2) =iIf( ComboBox1 = "Pre-payment" , " V ", Empty)
 Cells(6, 11) = iIf( ComboBox1 = "Pre-payment",  Empty , " V ")

Изменено: kuklp12.08.2017 10:32:08

Я сам — дурнее всякого примера! …

 

Equio

Пользователь

Сообщений: 274
Регистрация: 05.05.2016

#3

12.08.2017 09:34:36

Функция «And» в VBA (как, кстати, и в других языках программирования) применяется, когда требуется проверка одновременного выполнения двух или более условий. Она НЕ применяется для записи в одну строку нескольких команд. Команды в VBA записываются либо одна под другой, либо в одну строку через двоеточие.

Код
If (ComboBox1 = "Pre-payment") And (ComboBox2 = "Pre-payment")  Then
    Cells(6, 2) = "  V  "
    Cells(6, 11) = Empty
Else
    Cells(6, 11) = "  V  " : Cells(6, 2) = Empty
End If

Т.е. если Вы хотите перевести с человеческого языка на язык VBA такую конструкцию «если выполняется условие1, то выполнить действие1 и выполнить действие2», то несмотря на то, что в человеческом языке команды «выполнить действие1», «выполнить действие2» соединяются с помощью «и», на языке VBA в этом случае «and» не используется, эти две команды на выполнение действий либо записываются в двух разных строчках одна под другой, либо в одну строчку с двоеточием между ними. А если мы переводим с человеческого языка на язык VBA конструкцию «если одновременно выполняются условие1 и условие2, то выполнить действие1», то на языке VBA условие1 и условие2 записываются в одну строчку и между ними ставится «And».      

Изменено: Equio12.08.2017 09:58:58

 

ZVI

Пользователь

Сообщений: 4328
Регистрация: 23.12.2012

#4

12.08.2017 11:34:43

Цитата
Equio написал: Функция «And» в VBA … НЕ применяется для записи в одну строку нескольких команд.

Иногда все же применяется для побитовых (бинарных) операций: 2 Or 4,  5 And 3 , даже Not 2 , подробнее

здесь

. Но по данной теме все правильно написано :)

Изменено: ZVI12.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
Регистрация: 23.12.2012

Если бы продавцом был VBA, то он мог бы коварно спросить у покупателя: «Сколько взвесить арбузов и дынь?» и на ответ «5 и 3» взвесил бы 1 не знаю даже чего :)
MsgBox 3 And 5 выдаст 1

Изменено: ZVI12.08.2017 13:16:20

 

Equio

Пользователь

Сообщений: 274
Регистрация: 05.05.2016

ZVI, спасибо за интересное дополнение. Вам приходилось это использовать в решении какой-нибудь практической задачи?

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

:)
5 And 5 = 5
5 And 0 = 0
17 Or 2 =19

 

kuklp

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

#9

12.08.2017 14:48:34

Цитата
AlexBosenko написал:
как написать по другому?
Код
    ReDim a(1): a(1) = "V":
    Cells(6, 2) = a(-(ComboBox1 = "Pre-payment"))
    Cells(6, 11) = a((ComboBox1 = "Pre-payment") + 1)

Я сам — дурнее всякого примера! …

 

Equio

Пользователь

Сообщений: 274
Регистрация: 05.05.2016

#10

12.08.2017 15:13:29

Цитата
Все_просто написал:
Где-то читал, что это может несущественно сократить время работы макроса.

Ради интереса потестировал. В простейшем случае скорость одинаковая. Такой код

Код
a = Now
For i = 1 To 100000000
      S1 = S1 + i: S2 = S2 - S1 * 2
Next i
MsgBox (Now - a) * S2 / S1

даёт такое же время расчёта, как и без двоеточия в две строки.  

 

ZVI

Пользователь

Сообщений: 4328
Регистрация: 23.12.2012

#11

12.08.2017 15:27:37

Цитата
Equio написал: Вам приходилось это использовать в решении какой-нибудь практической задачи?
Код
' True когда (любая) размерность массива задана
Function IsArrayDim(Arr()) As Boolean
  IsArrayDim = Not Not Arr
End Function

Sub Test()
  
  Dim Arr()
  Debug.Print "массив не пустой = " & IsArrayDim(Arr)
  
  ReDim Arr(0 To 1)
  Debug.Print "массив не пустой = " & IsArrayDim(Arr)

End Sub
 

Equio

Пользователь

Сообщений: 274
Регистрация: 05.05.2016

#12

12.08.2017 16:41:31

ZVI, спасибо. Есть ли какие-то преимущества перед просто проверкой на Not(arr) = -1?

Изменено: Equio12.08.2017 16:55:07

В этом учебном материале вы узнаете, как использовать Excel функцию AND (в VBA) с синтаксисом и примерами.

Описание

Microsoft Excel функция AND возвращает true, если все условия true. Он возвращает false, если любое из условий — false.
Функция AND — это встроенная в Excel функция, которая относится к категории логических функций. Её можно использовать как функцию VBA в Excel.
В качестве функции VBA вы можете использовать эту функцию в коде макроса, который вводится через редактор Microsoft Visual Basic.
Пожалуйста, прочтите нашу страницу функции И (WS), если вы ищете версию функции И для рабочего листа, поскольку она имеет совершенно другой синтаксис.

Синтаксис

Синтаксис функции AND в Microsoft Excel:

condition1 And condition2 [… And condition_n]

Аргументы или параметры

condition1, condition2, … condition_n
Выражения, которые вы хотите проверить, могут иметь значение true или false.

Возвращаемое значение

Функция And возвращает true, если все условия true.
Функция And возвращает false, если любое из условий false.

Применение

  • Excel для Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 для Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Тип функции

  • Функция VBA

Пример (как функция VBA)

Давайте рассмотрим несколько примеров функции And, чтобы понять, как использовать Excel функцию And в коде Excel VBA. В этом первом примере функция And сочетается с оператором If в коде VBA:

If LWeb = «Yahoo.com» And LPages <= 10 Then

  LBand = «Low»

Else

  LBand = «High»

End If

В этой условной конструкции, переменной LBand будет присвоено строковое значение «Low», если значения LWeb = «Yahoo.com» и LPages <= 10. В противном случае для переменной LBand будет присвоено строковое значение «High».

Во втором примере используется оператор And функция с функцией Or в VBA, например:

If (LWeb = «Yahoo.com» Or LWeb = «Bing.com») And LPages<= 10 Then

  LBandwidth = «Low»

Else

  LBandwidth = «High»

End If

В этой условной конструкции для переменной LBand строковое значение «Low», если LWeb был либо «Yahoo.com», либо «Bing.com» и LPages<= 10. В противном случае для переменной LBand будет присвоено строковое значение «High».

На чтение 6 мин Опубликовано 15.12.2015

Содержание

  1. Операторы Excel VBA
  2. Математические операторы
  3. Строковые операторы
  4. Операторы сравнения
  5. Логические операторы
  6. Встроенные функции

Операторы Excel VBA

При написании кода VBA в Excel набор встроенных операторов используют на каждом шагу. Эти операторы делятся на математические, строковые, операторы сравнения и логические. Далее мы подробно рассмотрим каждую группу операторов.

Математические операторы

Основные математические операторы VBA перечислены в таблице ниже.

В правом столбце таблицы указан приоритет операторов, принятый по умолчанию при отсутствии скобок. Добавляя в выражение скобки, можно изменять порядок выполнения операторов VBA по своему желанию.

Оператор Действие Приоритет
(1 — высший; 5 — низший)
^ Оператор возведения в степень 1
* Оператор умножения 2
/ Оператор деления 2
Оператор деления без остатка – возвращает результат деления двух чисел без остатка. Например, 74 возвратит результат 1 3
Mod Оператор модуля (остатка) – возвращает остаток от деления двух чисел. Например, 8 Mod 3 возвратит результат 2. 4
+ Оператор сложения 5
Оператор вычитания 5

Строковые операторы

Основной строковый оператор в Excel VBA – это оператор конкатенации & (слияние):

Оператор Действие
& Оператор конкатенации. К примеру, выражение «A» & «B» возвратит результат AB.

Операторы сравнения

Операторы сравнения используются для сравнения двух чисел или строк и возвращают логическое значение типа Boolean (True или False). Основные операторы сравнения Excel VBA перечислены в этой таблице:

Оператор Действие
= Равно
<> Не равно
< Меньше
> Больше
<= Меньше либо равно
>= Больше либо равно

Логические операторы

Логические операторы, как и операторы сравнения, возвращают логическое значение типа Boolean (True или False). Основные логические операторы Excel VBA перечислены в таблице ниже:

Оператор Действие
And Операция конъюнкции, логический оператор И. Например, выражение A And B возвратит True, если A и B оба равны True, в противном случае возвратит False.
Or Операция дизъюнкции, логический оператор ИЛИ. Например, выражение A Or B возвратит True, если A или B равны True, и возвратит False, если A и B оба равны False.
Not Операция отрицания, логический оператор НЕ. Например, выражение Not A возвратит True, если A равно False, или возвратит False, если A равно True.

В приведённой выше таблице перечислены не все логические операторы, доступные в VBA. Полный список логических операторов можно найти на сайте Visual Basic Developer Center.

Встроенные функции

В VBA доступно множество встроенных функций, которые могут быть использованы при написании кода. Ниже перечислены некоторые из наиболее часто используемых:

Функция Действие
Abs Возвращает абсолютную величину заданного числа.

Пример:

  • Abs(-20) возвращает значение 20;
  • Abs(20) возвращает значение 20.
Chr Возвращает символ ANSI, соответствующий числовому значению параметра.

Пример:

  • Chr(10) возвращает перенос строки;
  • Chr(97) возвращает символ a.
Date Возвращает текущую системную дату.
DateAdd Добавляет определённый временной интервал к заданной дате. Синтаксис функции:

DateAdd(интервал, число, дата)

Где аргумент интервал определяет тип временного интервала, добавляемого к заданной дате в количестве, указанном в аргументе число.

Аргумент интервал может принимать одно из следующих значений:

Интервал Значение
yyyy год
q квартал
m месяц
y день года
d день
w день недели
ww неделя
h час
n минута
s секунда

Пример:

  • DateAdd(«d», 32, «01/01/2015») добавляет 32 дня к дате 01/01/2015 и, таким образом, возвращает дату 02/02/2015.
  • DateAdd(«ww», 36, «01/01/2015») добавляет 36 недель к дате 01/01/2015 и возвращает дату 09/09/2015.
DateDiff Вычисляет количество определённых временных интервалов между двумя заданными датами.

Пример:

  • DateDiff(«d», «01/01/2015», «02/02/2015») вычисляет количество дней между датами 01/01/2015 и 02/02/2015, возвращает результат 32.
  • DateDiff(«ww», «01/01/2015», «03/03/2016») вычисляет количество недель между датами 01/01/2015 и 03/03/2016, возвращает результат 61.
Day Возвращает целое число, соответствующее дню месяца в заданной дате.

Пример: Day(«29/01/2015») возвращает число 29.

Hour Возвращает целое число, соответствующее количеству часов в заданном времени.

Пример: Hour(«22:45:00») возвращает число 22.

InStr Принимает в качестве аргументов целое число и две строки. Возвращает позицию вхождения второй строки внутри первой, начиная поиск с позиции, заданной целым числом.

Пример:

  • InStr(1, «Вот искомое слово», «слово») возвращает число 13.
  • InStr(14, «Вот искомое слово, а вот еще искомое слово», «слово») возвращает число 38.

Примечание: Аргумент-число может быть не задан, в таком случае поиск начинается с первого символа строки, заданной во втором аргументе функции.

Int Возвращает целую часть заданного числа.

Пример: Int(5.79) возвращает результат 5.

Isdate Возвращает True, если заданное значение является датой, или False – если датой не является.

Пример:

  • IsDate(«01/01/2015») возвращает True;
  • IsDate(100) возвращает False.
IsError Возвращает True, если заданное значение является ошибкой, или False – если ошибкой не является.
IsMissing В качестве аргумента функции передаётся имя необязательного аргумента процедуры. IsMissing возвращает True, если для рассматриваемого аргумента процедуры не передано значение.
IsNumeric Возвращает True, если заданное значение может быть рассмотрено как число, в противном случае возвращает False.
Left Возвращает заданное количество символов от начала переданной строки. Синтаксис функции вот такой:

Left(строка, длина)

где строка – это исходная строка, а длина – количество возвращаемых символов, считая от начала строки.

Пример:

  • Left(«абвгдежзиклмн», 4) возвращает строку «абвг»;
  • Left(«абвгдежзиклмн», 1) возвращает строку «а».
Len Возвращает количество символов в строке.

Пример: Len(«абвгдеж») возвращает число 7.

Month Возвращает целое число, соответствующее месяцу в заданной дате.

Пример: Month(«29/01/2015») возвращает значение 1.

Mid Возвращает заданное количество символов из середины переданной строки. Синтаксис функции:

Mid(строка, начало, длина)

где строка – это исходная строка, начало – позиция начала извлекаемой строки, длина – количество символов, которые требуется извлечь.

Пример:

  • Mid(«абвгдежзиклмн», 4, 5) возвращает строку «гдежз»;
  • Mid(«абвгдежзиклмн», 10, 2) возвращает строку «кл».
Minute Возвращает целое число, соответствующее количеству минут в заданном времени.Пример: Minute(«22:45:15») возвращает значение 45.
Now Возвращает текущую системную дату и время.
Right Возвращает заданное количество символов от конца переданной строки. Синтаксис функции:

Right(строка, длина)

Где строка – это исходная строка, а длина – это количество символов, которые надо извлечь, считая от конца заданной строки.

Пример:

  • Right(«абвгдежзиклмн», 4) возвращает строку «клмн»;
  • Right(«абвгдежзиклмн», 1) возвращает строку «н».
Second Возвращает целое число, соответствующее количеству секунд в заданном времени.

Пример: Second(«22:45:15») возвращает значение 15.

Sqr Возвращает квадратный корень числовой величины, переданной в аргументе.

Пример:

  • Sqr(4) возвращает значение 2;
  • Sqr(16) возвращает значение 4.
Time Возвращает текущее системное время.
Ubound Возвращает верхний индекс измерения заданного массива.

Примечание: Для многомерных массивов в качестве необязательного аргумента может быть указано, индекс какого именно измерения нужо возвратить. Если не указано, то по умолчанию равно 1.

Year Возвращает целое число, соответствующее году в заданной дате.Пример: Year(«29/01/2015») возвращает значение 2015.

Данный список включает в себя только избранные наиболее часто употребляемые встроенные функции Excel Visual Basic. Исчерпывающий список функций VBA, доступных для использования в макросах Excel, можно найти на сайте Visual Basic Developer Center.

Оцените качество статьи. Нам важно ваше мнение:

Понравилась статья? Поделить с друзьями:
  • Функция aggregate в excel
  • Функция abs по русски excel
  • Функция abs в функции если в excel
  • Функция abs в excel что это
  • Функция abs в excel для чего