If this and that then this in excel

Содержание

  1. IF function
  2. Simple IF examples
  3. Common problems
  4. Need more help?
  5. Using IF with AND, OR and NOT functions
  6. Examples
  7. Using AND, OR and NOT with Conditional Formatting
  8. Need more help?
  9. See also
  10. If cell is this OR that
  11. Related functions
  12. Summary
  13. Generic formula
  14. Explanation
  15. Increase price if color is red or green
  16. If this AND that OR that
  17. Related functions
  18. Summary
  19. Generic formula
  20. Explanation
  21. Dave Bruns
  22. Проверка условий (If…Then…)
  23. Краткое руководство по VBA If Statement
  24. Что такое IF и зачем оно тебе?
  25. Тестовые данные
  26. Формат операторов VBA If Then
  27. Простой пример If Then
  28. Условия IF
  29. Использование If ElseIf
  30. Использование If Else
  31. Используя If And/If Or
  32. Функция IIF
  33. Использование Select Case

IF function

The IF function is one of the most popular functions in Excel, and it allows you to make logical comparisons between a value and what you expect.

So an IF statement can have two results. The first result is if your comparison is True, the second if your comparison is False.

For example, =IF(C2=”Yes”,1,2) says IF(C2 = Yes, then return a 1, otherwise return a 2).

Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it’s false.

IF(logical_test, value_if_true, [value_if_false])

The condition you want to test.

The value that you want returned if the result of logical_test is TRUE.

The value that you want returned if the result of logical_test is FALSE.

Simple IF examples

In the above example, cell D2 says: IF(C2 = Yes, then return a 1, otherwise return a 2)

In this example, the formula in cell D2 says: IF(C2 = 1, then return Yes, otherwise return No)As you see, the IF function can be used to evaluate both text and values. It can also be used to evaluate errors. You are not limited to only checking if one thing is equal to another and returning a single result, you can also use mathematical operators and perform additional calculations depending on your criteria. You can also nest multiple IF functions together in order to perform multiple comparisons.

B2,”Over Budget”,”Within Budget”)» loading=»lazy»>

=IF(C2>B2,”Over Budget”,”Within Budget”)

In the above example, the IF function in D2 is saying IF(C2 Is Greater Than B2, then return “Over Budget”, otherwise return “Within Budget”)

B2,C2-B2,»»)» loading=»lazy»>

In the above illustration, instead of returning a text result, we are going to return a mathematical calculation. So the formula in E2 is saying IF(Actual is Greater than Budgeted, then Subtract the Budgeted amount from the Actual amount, otherwise return nothing).

In this example, the formula in F7 is saying IF(E7 = “Yes”, then calculate the Total Amount in F5 * 8.25%, otherwise no Sales Tax is due so return 0)

Note: If you are going to use text in formulas, you need to wrap the text in quotes (e.g. “Text”). The only exception to that is using TRUE or FALSE, which Excel automatically understands.

Common problems

What went wrong

There was no argument for either value_if_true or value_if_False arguments. To see the right value returned, add argument text to the two arguments, or add TRUE or FALSE to the argument.

This usually means that the formula is misspelled.

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Источник

Using IF with AND, OR and NOT functions

The IF function allows you to make a logical comparison between a value and what you expect by testing for a condition and returning a result if that condition is True or False.

=IF(Something is True, then do something, otherwise do something else)

But what if you need to test multiple conditions, where let’s say all conditions need to be True or False ( AND), or only one condition needs to be True or False ( OR), or if you want to check if a condition does NOT meet your criteria? All 3 functions can be used on their own, but it’s much more common to see them paired with IF functions.

Use the IF function along with AND, OR and NOT to perform multiple evaluations if conditions are True or False.

IF(AND()) — IF(AND(logical1, [logical2], . ), value_if_true, [value_if_false]))

IF(OR()) — IF(OR(logical1, [logical2], . ), value_if_true, [value_if_false]))

IF(NOT()) — IF(NOT(logical1), value_if_true, [value_if_false]))

The condition you want to test.

The value that you want returned if the result of logical_test is TRUE.

The value that you want returned if the result of logical_test is FALSE.

Here are overviews of how to structure AND, OR and NOT functions individually. When you combine each one of them with an IF statement, they read like this:

AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False)

OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False)

NOT – =IF(NOT(Something is True), Value if True, Value if False)

Examples

Following are examples of some common nested IF(AND()), IF(OR()) and IF(NOT()) statements. The AND and OR functions can support up to 255 individual conditions, but it’s not good practice to use more than a few because complex, nested formulas can get very difficult to build, test and maintain. The NOT function only takes one condition.

Here are the formulas spelled out according to their logic:

=IF(AND(A2>0,B2 0,B4 50),TRUE,FALSE)

IF A6 (25) is NOT greater than 50, then return TRUE, otherwise return FALSE. In this case 25 is not greater than 50, so the formula returns TRUE.

IF A7 (“Blue”) is NOT equal to “Red”, then return TRUE, otherwise return FALSE.

Note that all of the examples have a closing parenthesis after their respective conditions are entered. The remaining True/False arguments are then left as part of the outer IF statement. You can also substitute Text or Numeric values for the TRUE/FALSE values to be returned in the examples.

Here are some examples of using AND, OR and NOT to evaluate dates.

Here are the formulas spelled out according to their logic:

IF A2 is greater than B2, return TRUE, otherwise return FALSE. 03/12/14 is greater than 01/01/14, so the formula returns TRUE.

=IF(AND(A3>B2,A3 B2,A4 B2),TRUE,FALSE)

IF A5 is not greater than B2, then return TRUE, otherwise return FALSE. In this case, A5 is greater than B2, so the formula returns FALSE.

Using AND, OR and NOT with Conditional Formatting

You can also use AND, OR and NOT to set Conditional Formatting criteria with the formula option. When you do this you can omit the IF function and use AND, OR and NOT on their own.

From the Home tab, click Conditional Formatting > New Rule. Next, select the “ Use a formula to determine which cells to format” option, enter your formula and apply the format of your choice.

Edit Rule dialog showing the Formula method» loading=»lazy»>

Using the earlier Dates example, here is what the formulas would be.

If A2 is greater than B2, format the cell, otherwise do nothing.

=AND(A3>B2,A3 B2,A4 B2)

If A5 is NOT greater than B2, format the cell, otherwise do nothing. In this case A5 is greater than B2, so the result will return FALSE. If you were to change the formula to =NOT(B2>A5) it would return TRUE and the cell would be formatted.

Note: A common error is to enter your formula into Conditional Formatting without the equals sign (=). If you do this you’ll see that the Conditional Formatting dialog will add the equals sign and quotes to the formula — =»OR(A4>B2,A4

Need more help?

​​​​​​​

See also

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Источник

If cell is this OR that

Summary

To do something when a cell is this or that (i.e. a cell is equal to «x», «y», etc.) you can use the IF function together with the OR function to run a test. In cell D6, the formula is:

which returns «x» when B6 contains «red» or «green», and an empty string («») if not. Notice the OR function is not case-sensitive.

Generic formula

Explanation

In the example shown, we want to mark or «flag» records where the color is red OR green. In other words, we want to check the color in column B, and then leave a marker (x) if we find the word «red» or «green». In D6, the formula were using is:

This is an example of nesting – the OR function is nested inside the IF function. Working from the inside-out, the logical test is created with the OR function:

OR will return TRUE if the value in B6 is either «red» OR «green», and FALSE if not. This result is returned directly to the IF function as the logical_test argument. The color in B6 is «red» so OR returns TRUE:

With TRUE as the result of the logical test, the IF function returns a final result of «x».

When the color in column B is not red or green, the OR function will return FALSE, and IF will return an empty string («») which looks like a blank cell:

As the formula is copied down the column, the result is either «x» or «», depending on the colors in column B.

Note: if an empty string («») is not provided for value_if_false, the formula will return FALSE when the color is not red or green.

Increase price if color is red or green

You can extend this formula to run another calculation, instead of simply returning «x».

For example, let’s say you want to increase the price of red and green items only by 15%. In that case, you can use the formula in column E to calculate a new price:

The logical test is the same as before. However the value_if_true argument is now a formula:

When the result of the test is TRUE, we multiply the original price in column C by 1.15, to increase by 15%. If the result of the test is FALSE, we simply return the original price. As the formula is copied down, the result is either the increased price or original price, depending on the color.

Источник

If this AND that OR that

Summary

To test for various combinations of this AND that, or this OR that, you can use the IF function with the AND and OR functions. In the example shown, the formula in D6 is:

When an item is «red», and either «small» or «medium», the formula returns «x». All other combinations return an empty string («»).

Generic formula

Explanation

In the example shown, we simply want to «mark» or «flag» rows where the color is «red» AND size is either «small» or «medium». To return TRUE when items are red and small, we can use a logical statement constructed with the AND function:

To extend the statement to return TRUE when items are red and either small or medium, we can nest the OR function inside the AND function like this:

This snippet will return TRUE only if the value in B6 is «red» AND the value in C6 is either «small» or «medium». It is placed inside the IF function as the logical test. When the logical test returns TRUE, the IF function returns «x». When the logical test returns FALSE, the IF function returns an empty string («»).

Change the values returned by IF to suit your needs.

Dave Bruns

Hi — I’m Dave Bruns, and I run Exceljet with my wife, Lisa. Our goal is to help you work faster in Excel. We create short videos, and clear examples of formulas, functions, pivot tables, conditional formatting, and charts.

Источник

Проверка условий (If…Then…)

Угадай, если сможешь, и выбери, если посмеешь

Краткое руководство по VBA If Statement

Описание Формат Пример
If Then If [условие верно]
Then [действие]
End If
If score = 100
Then Debug.Print
«Отлично»
End If
If Else If [условие верно]
Then [действие]
Else [действие]
End If
If score = 100
Then Debug.Print
«Отлично»
Else Debug.Print
«Попробуй снова»
End If
If ElseIf If [1 условие верно]
Then [действие]
ElseIf [2 условие
верно]
Then [действие]
End If
If score = 100
Then Debug.Print
«Отлично»
ElseIf score > 50
Then Debug.Print
«Пройдено»
ElseIf score 50
Then Debug.Print
«Пройдено»
ElseIf score > 30
Then Debug.Print
«Попробуй снова»
Else Debug.Print
«Ой»
End If
If без Endif
(Только одна
строка)
If [условие верно]
Then [действие]
If value

В следующем коде показан простой пример использования оператора VBA If

Что такое IF и зачем оно тебе?

Оператор VBA If используется, чтобы позволить вашему коду делать выбор, когда он выполняется.

Вам часто захочется сделать выбор на основе данных, которые читает ваш макрос.

Например, вы можете захотеть читать только тех учеников, у которых оценки выше 70. Когда вы читаете каждого учащегося, вы можете использовать инструкцию If для проверки отметок каждого учащегося.

Важным словом в последнем предложении является проверка. Оператор If используется для проверки значения, а затем для выполнения задачи на основе результатов этой проверки.

Тестовые данные

Мы собираемся использовать следующие тестовые данные для примеров кода в этом посте.

Формат операторов VBA If Then

Формат оператора If Then следующий

За ключевым словом If следуют условие и ключевое слово Then

Каждый раз, когда вы используете оператор If Then, вы должны использовать соответствующий оператор End If.

Когда условие оценивается как истинное, обрабатываются все строки между If Then и End If.

Чтобы сделать ваш код более читабельным, рекомендуется делать отступы между операторами If Then и End If.

Отступ между If и End If

Отступ означает просто переместить строку кода на одну вкладку вправо. Правило большого пальца состоит в том, чтобы сделать отступ между начальным и конечным операторами, такими как:

Sub … End Sub
If Then … End If
If Then… ElseIf … Else … Endif
For … Next
Do While … Loop
Select Case … End Case

Для отступа в коде вы можете выделить строки для отступа и нажать клавишу Tab. Нажатие клавиш Shift + Tab сделает отступ кода, т.е. переместит его на одну вкладку влево.

Вы также можете использовать значки на панели инструментов Visual Basic для отступа кода.

Если вы посмотрите на примеры кода на этом сайте, вы увидите, что код имеет отступ.

Простой пример If Then

Следующий код выводит имена всех студентов с баллами более 50.

  • Василий Кочин
  • Максим Бородин
  • Дмитрий Маренин
  • Олеся Клюева
  • Евгений Яшин

Поэкспериментируйте с этим примером и проверьте значение или знак > и посмотрите, как изменились результаты.

Условия IF

Часть кода между ключевыми словами If и Then называется условием. Условие — это утверждение, которое оценивается как истинное или ложное. Они в основном используются с операторами Loops и If. При создании условия вы используете такие знаки, как «>, ,> =,

Условие Это верно, когда
x 5 x больше, чем 5
x >= 5 x больше, либо равен 5
x = 5 x равен 5
x <> 5 x не равен 5
x > 5 And x 10 x равен 2 ИЛИ x больше,чем 10
Range(«A1») = «Иван» Ячейка A1 содержит текст «Иван»
Range(«A1») <> «Иван» Ячейка A1 не содержит текст «Иван»

Вы могли заметить x = 5, как условие. Не стоит путать с х = 5, при использовании в качестве назначения.

Когда в условии используется «=», это означает, что «левая сторона равна правой стороне».

В следующей таблице показано, как знак равенства используется в условиях и присваиваниях.

Использование «=» Тип Значение
Loop Until x = 5 Условие Равен ли x пяти
Do While x = 5 Условие Равен ли x пяти
If x = 5 Then Условие Равен ли x пяти
For x = 1 To 5 Присваивание Установите значение х = 1, потом = 2 и т.д.
x = 5 Присваивание Установите х до 5
b = 6 = 5 Присваивание и
условие
Присвойте b
результату условия
6 = 5
x = MyFunc(5,6) Присваивание Присвойте х
значение,
возвращаемое
функцией

Последняя запись в приведенной выше таблице показывает оператор с двумя равными. Первый знак равенства — это присвоение, а любые последующие знаки равенства — это условия.

Поначалу это может показаться странным, но подумайте об этом так. Любое утверждение, начинающееся с переменной и равно, имеет следующий формат

[переменная] [=] [оценить эту часть]

Поэтому все, что находится справа от знака равенства, оценивается и результат помещается в переменную. Посмотрите на последние три строки таблицы, как:

Использование If ElseIf

Инструкция ElseIf позволяет вам выбирать из нескольких вариантов. В следующем примере мы печатаем баллы, которые находятся в диапазоне.

Важно понимать, что порядок важен. Условие If проверяется первым.

Если это правда, то печатается «Высший балл», и оператор If заканчивается.

Если оно ложно, то код переходит к следующему ElseIf и проверяет его состояние.

Давайте поменяемся местами If и ElseIf из последнего примера. Код теперь выглядит так

В этом случае мы сначала проверяем значение более 75. Мы никогда не будем печатать «Высший балл», потому что, если значение больше 85, это вызовет первый оператор if.

Чтобы избежать подобных проблем, мы должны использовать два условия. Они помогают точно указать, что вы ищете, чтобы избежать путаницы. Пример ниже показывает, как их использовать. Мы рассмотрим более многочисленные условия в разделе ниже.

Давайте расширим оригинальный код. Вы можете использовать столько операторов ElseIf, сколько захотите. Мы добавим еще несколько, чтобы учесть все наши классификации баллов.

Использование If Else

Утверждение Else используется, как ловушка для всех. Это в основном означает «если бы не было условий» или «все остальное». В предыдущем примере кода мы не включили оператор печати для метки сбоя. Мы можем добавить это, используя Else.

Так что, если это не один из других типов, то это провал.

Давайте напишем некоторый код с помощью наших примеров данных и распечатаем студента и его классификацию.

Результаты выглядят так: в столбце E — классификация баллов

Используя If And/If Or

В выражении If может быть несколько условий. Ключевые слова VBA And и Or позволяют использовать несколько условий.

Эти слова работают так же, как вы используете их на английском языке.

Давайте снова посмотрим на наши примеры данных. Теперь мы хотим напечатать всех студентов, которые набрали от 50 до 80 баллов.

Мы используем Аnd, чтобы добавить дополнительное условие. Код гласит: если оценка больше или равна 50 и меньше 75, напечатайте имя студента.

Вывести имя и фамилию в результаты:

  • Дмитрий Маренин
  • Олеся Клюева
  • Евгений Яшин

В нашем следующем примере мы хотим знать, кто из студентов сдавал историю или геометрию. Таким образом, в данном случае мы говорим, изучал ли студент «История» ИЛИ изучал ли он «Геометрия» (Ctrl+G).

  • Василий Кочин
  • Александр Грохотов
  • Дмитрий Маренин
  • Николай Куликов
  • Олеся Клюева
  • Наталия Теплых
  • Дмитрий Андреев

Использование нескольких таких условий часто является источником ошибок. Эмпирическое правило, которое нужно помнить, должно быть максимально простым.

Использование IF AND

And работает следующим образом:

Условие 1 Условие 2 Результат
ИСТИНА ИСТИНА ИСТИНА
ИСТИНА ЛОЖЬ ЛОЖЬ
ЛОЖЬ ИСТИНА ЛОЖЬ
ЛОЖЬ ЛОЖЬ ЛОЖЬ

Что вы заметите, так это то, что And верно только тогда, когда все условия выполняются.

Использование IF OR

Ключевое слово OR работает следующим образом

Условие 1 Условие 2 Результат
ИСТИНА ИСТИНА ИСТИНА
ИСТИНА ЛОЖЬ ИСТИНА
ЛОЖЬ ИСТИНА ИСТИНА
ЛОЖЬ ЛОЖЬ ЛОЖЬ

Что вы заметите, так это то, что OR ложно, только когда все условия ложны.

Смешивание And и Or может затруднить чтение кода и привести к ошибкам. Использование скобок может сделать условия более понятными.

Использование IF NOT

Также есть оператор NOT. Он возвращает противоположный результат условия.

Условие Результат
ИСТИНА ЛОЖЬ
ЛОЖЬ ИСТИНА

Следующие две строки кода эквивалентны.

Помещение условия в круглые скобки облегчает чтение кода

Распространенное использование Not — при проверке, был ли установлен объект. Возьмите Worksheet для примера. Здесь мы объявляем рабочий лист.

Мы хотим проверить действительность mySheet перед его использованием. Мы можем проверить, если это Nothing.

Нет способа проверить, является ли это чем-то, поскольку есть много разных способов, которым это может быть что-то. Поэтому мы используем NOT с Nothing.

Если вы находите это немного запутанным, вы можете использовать круглые скобки, как здесь

Функция IIF

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

= ЕСЛИ (F2 =»»,»», F1 / F2)

= If (условие, действие, если ИСТИНА, действие, если ЛОЖЬ).

VBA имеет функцию IIf, которая работает так же. Давайте посмотрим на примере. В следующем коде мы используем IIf для проверки значения переменной val. Если значение больше 10, мы печатаем ИСТИНА, в противном случае мы печатаем ЛОЖЬ.

В нашем следующем примере мы хотим распечатать «Удовлетворитеьно» или «Незачет» рядом с каждым студентом в зависимости от их баллов. В первом фрагменте кода мы будем использовать обычный оператор VBA If, чтобы сделать это.

В следующем фрагменте кода мы будем использовать функцию IIf. Код здесь намного аккуратнее.

Функция IIf очень полезна для простых случаев, когда вы имеете дело с двумя возможными вариантами.

Использование Nested IIf

Вы также можете вкладывать IIf-операторы, как в Excel. Это означает использование результата одного IIf с другим. Давайте добавим еще один тип результата в наши предыдущие примеры. Теперь мы хотим напечатать «Отлично», «Удовлетворительно» или «Незачетт» для каждого студента.

Используя обычный VBA, мы сделали бы это так

Используя вложенные IIfs, мы могли бы сделать это так

Использование вложенного IIf хорошо в простых случаях, подобных этому. Код прост для чтения и, следовательно, вряд ли вызовет ошибки.

Чего нужно остерегаться

Важно понимать, что функция IIf всегда оценивает как Истинную, так и Ложную части выражения независимо от условия.

В следующем примере мы хотим разделить по баллам, когда он не равен нулю. Если он равен нулю, мы хотим вернуть ноль.

Однако, когда отметки равны нулю, код выдаст ошибку «Делить на ноль». Это потому, что он оценивает как Истинные, так и Ложные утверждения. Здесь ложное утверждение, т.е. (60 / Marks), оценивается как ошибка, потому что отметки равны нулю.

Если мы используем нормальный оператор IF, он будет запускать только соответствующую строку.

Это также означает, что если у вас есть функции для ИСТИНА и ЛОЖЬ, то обе будут выполнены. Таким образом, IIF будет запускать обе функции, даже если он использует только одно возвращаемое значение. Например:

IF против IIf

В этом случае вы можете видеть, что IIf короче для написания и аккуратнее. Однако если условия усложняются, вам лучше использовать обычное выражение If. Недостатком IIf является то, что он недостаточно известен, поэтому другие пользователи могут не понимать его так же, как и код, написанный с помощью обычного оператора if.

Кроме того, как мы обсуждали в последнем разделе, IIF всегда оценивает части ИСТИНА и ЛОЖЬ, поэтому, если вы имеете дело с большим количеством данных, оператор IF будет быстрее.

Мое эмпирическое правило заключается в том, чтобы использовать IIf, когда он будет прост для чтения и не требует вызовов функций. Для более сложных случаев используйте обычный оператор If.

Использование Select Case

Оператор Select Case — это альтернативный способ написания статистики If с большим количеством ElseIf. Этот тип операторов вы найдете в большинстве популярных языков программирования, где он называется оператором Switch. Например, Java, C #, C ++ и Javascript имеют оператор switch.

Давайте возьмем наш пример DobClass сверху и перепишем его с помощью оператора Select Case.

Ниже приведен тот же код с использованием оператора Select Case. Главное, что вы заметите, это то, что мы используем “Case 85 to 100” rather than “marks >=85 And marks =85 And marks

Ответ на упражнение

Следующий код показывает, как выполнить вышеупомянутое упражнение.

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

Источник

Explanation 

To do something specific when two or more conditions are TRUE, you can use the IF function in combination with the AND function to evaluate conditions with a test, then take one action if the result is TRUE, and (optionally) do take another if the result of the test is FALSE.

In the example shown, we simply want to «flag» records where the color is red AND the size is small. In other words, we want to check cells in column B for the color «red» AND check cells in column C to see if the size is «small». Then, if both conditions are TRUE, we mark the row with an «x». In D6, the formula is:

=IF(AND(B6="red",C6="small"),"x","")

In this formula, the logical test is this bit:

AND(B6="red",C6="small")

This snippet will return TRUE only if the value in B6 is «red» AND the value in C6 is «small». If either condition isn’t true, the test will return FALSE.

Next, we need to take an action when the result of the test is TRUE. In this case, we do that by adding an «x» to column D. If the test is FALSE,  we simply add an empty string («»). This causes an «x» to appear in column D when both conditions are true and nothing to display if not.

Note: if we didn’t add the empty string when FALSE, the formula would actually display FALSE whenever the color is not red.

Testing the same cell

In the example above, we are checking two different cells, but there nothing that prevents you from running two tests on the same cell. For example, let’s say you want to check values in column A and then do something when a value at least 100 but less than 200.  In that case you could use this code for the logical test:

=AND(A1>=100,A1<200)

While working with Excel, we are able to evaluate two or more conditions and customize the actions by using the IF and AND functions.  This step by step tutorial will assist all levels of Excel users in marking items in a database that satisfy two conditions.  

Figure 1. Final result: IF this AND that

Final formula: =IF(AND(C3="Non-Reusable",D3="Plastic"),"x","")

Syntax of IF Function

IF function evaluates a given logical test and returns a TRUE or a FALSE

=IF(logical_test, [value_if_true], [value_if_false])

  • The arguments “value_if_true” and “value_if_false” are optional.  If left blank, the function will return TRUE if the logical test is met, and FALSE if otherwise.  

Syntax of AND Function

AND function evaluates all logical tests and returns a TRUE if all arguments are TRUE; FALSE if one or more arguments is FALSE

=AND(logical1, [logical2], ...)

Parameters:

  • logical1–  the first condition that we want to test
  • only logical1 is required; succeeding conditions are optional  

Setting up Our Data

Our table contains a list of Item ID (column B), Category (column C), Material (column D) and Indicator (column E). In cells E3:E9, we want to indicate whether an item is a “Non-Reusable Plastic” or not.  

Figure 2. Sample data for IF this AND that

IF “Non-Reusable” AND “Plastic”

In order to mark an item if it is both “Non-Reusable” and made of “Plastic”, we follow these steps:

Step 1.  Select cell E3

Step 2.  Enter the formula: =IF(AND(C3="Non-Reusable",D3="Plastic"),"x","")

Step 3: Press ENTER

Step 4: Copy the formula in cell E3 to cells E4:E9 by clicking the “+” icon at the bottom right-corner of cell E3 and dragging it down.  

Figure 3. Entering the formula to mark IF “Non-Reusable” AND “Plastic”

The first part of our formula tests two conditions using the AND function: if the category of an item is “Non-Reusable”, and if the material is “Plastic”.  When both conditions are satisfied, the IF function returns the character “x”, which marks the item as a “Non-Reusable Plastic”.  Otherwise, it returns an empty string “”.  

As a result, our formula returns an “x” in cells E3, E6 and E8, which satisfy our two conditions.  

Figure 4. Output: Mark “x” IF “Non-Reusable” AND “Plastic”

Most of the time, the problem you will need to solve will be more complex than a simple application of a formula or function. If you want to save hours of research and frustration, try our live Excelchat service! Our Excel Experts are available 24/7 to answer any Excel question you may have. We guarantee a connection within 30 seconds and a customized solution within 20 minutes.

IF function

The IF function is one of the most popular functions in Excel, and it allows you to make logical comparisons between a value and what you expect.

So an IF statement can have two results. The first result is if your comparison is True, the second if your comparison is False.

For example, =IF(C2=”Yes”,1,2) says IF(C2 = Yes, then return a 1, otherwise return a 2).

Your browser does not support video. Install Microsoft Silverlight, Adobe Flash Player, or Internet Explorer 9.

Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it’s false.

IF(logical_test, value_if_true, [value_if_false])

For example:

  • =IF(A2>B2,»Over Budget»,»OK»)

  • =IF(A2=B2,B4-A4,»»)

Argument name

Description

logical_test    (required)

The condition you want to test.

value_if_true    (required)

The value that you want returned if the result of logical_test is TRUE.

value_if_false    (optional)

The value that you want returned if the result of logical_test is FALSE.

Simple IF examples

Cell D2 contains a formula =IF(C2="Yes",1,2)

  • =IF(C2=”Yes”,1,2)

In the above example, cell D2 says: IF(C2 = Yes, then return a 1, otherwise return a 2)

Cell D2 contains the formula =IF(C2=1,"YES","NO")

  • =IF(C2=1,”Yes”,”No”)

In this example, the formula in cell D2 says: IF(C2 = 1, then return Yes, otherwise return No)As you see, the IF function can be used to evaluate both text and values. It can also be used to evaluate errors. You are not limited to only checking if one thing is equal to another and returning a single result, you can also use mathematical operators and perform additional calculations depending on your criteria. You can also nest multiple IF functions together in order to perform multiple comparisons.

Formula in cell D2 is =IF(C2>B2,”Over Budget”,”Within Budget”)

  • =IF(C2>B2,”Over Budget”,”Within Budget”)

In the above example, the IF function in D2 is saying IF(C2 Is Greater Than B2, then return “Over Budget”, otherwise return “Within Budget”)

Formula in cell E2 is =IF(C2>B2,C2-B2,"")

  • =IF(C2>B2,C2-B2,0)

In the above illustration, instead of returning a text result, we are going to return a mathematical calculation. So the formula in E2 is saying IF(Actual is Greater than Budgeted, then Subtract the Budgeted amount from the Actual amount, otherwise return nothing).

Formula in Cell F7 is IF(E7=”Yes”,F5*0.0825,0)

  • =IF(E7=”Yes”,F5*0.0825,0)

In this example, the formula in F7 is saying IF(E7 = “Yes”, then calculate the Total Amount in F5 * 8.25%, otherwise no Sales Tax is due so return 0)

Note: If you are going to use text in formulas, you need to wrap the text in quotes (e.g. “Text”). The only exception to that is using TRUE or FALSE, which Excel automatically understands.

Common problems

Problem

What went wrong

0 (zero) in cell

There was no argument for either value_if_true or value_if_False arguments. To see the right value returned, add argument text to the two arguments, or add TRUE or FALSE to the argument.

#NAME? in cell

This usually means that the formula is misspelled.

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Connect with an expert. Learn from live instructors.

See Also

IF function — nested formulas and avoiding pitfalls

IFS function

Using IF with AND, OR and NOT functions

COUNTIF function

How to avoid broken formulas

Overview of formulas in Excel

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

I have two tabels looking like this:
enter image description here

As you can see I have an empty column «OSAKAAL». I want excel to copy the correct values there, so if it finds exactly the same «KR_kood» and «Aasta» value on the left which is on the right table also, then it copies the «OSAKAAL2» value to the «OSAKAAL» cell.

asked Apr 3, 2017 at 19:14

M.P.'s user avatar

You can use a multi-criteria Index/Match for this. Make sure to enter with CTRL+SHIFT+ENTER as it’s an array formula.

In Q2, you can use:

=INDEX($J$2:$J$7,MATCH($O2&$P2,$L$2:$L$7&$K$2:$K$7,0))

(Adjust the ranges as necessary).

answered Apr 3, 2017 at 19:24

BruceWayne's user avatar

BruceWayneBruceWayne

22.8k15 gold badges64 silver badges109 bronze badges

0

You may try this Regular Formula which doesn’t require any special key stroke.
In Q2

=IFERROR(INDEX($J$2:$J$1000,MATCH(O2&P2,INDEX($L$2:$L$1000&$K$2:$K$1000,),0)),"")

Adjust the ranges used in the formula as per your requirement.

answered Apr 3, 2017 at 19:33

Subodh Tiwari sktneer's user avatar

Понравилась статья? Поделить с друзьями:
  • If there is a word better than love it would be you
  • If then with range in excel
  • If then goto in excel
  • If then else vba excel примеры
  • If then else for vba excel