If value like excel

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?

I have a column(x) and trying to do a If and like in another column(d). Getting a range error on the selection autofill part.

Dim src As Range
Set src = Worksheets("File").Range("2:17783")


    If (Range("x2").Value Like "*ProductType:'FXD';*") Then
                         Range("D2").Value = "FXD"
            ElseIf (Range("x2").Value Like "*;ProductSubType:'SWLEG'*") Then
                         Range("D2").Value = "XSW" 
            End If 

Selection.AutoFill Destination:=src.Columns("D")

asked Sep 29, 2017 at 17:41

excelguy's user avatar

excelguyexcelguy

1,5643 gold badges31 silver badges63 bronze badges

7

Instead of doing autofill just set the value at once.

Also do not forget to provide the sheet parent to all your range objects:

Dim src As Range
Set src = Worksheets("File").Range("2:17783")


If (Worksheets("File").Range("x2").Value Like "*ProductType:'FXD';*") Then
    Worksheets("File").Range("D2:D17783").Value = "FXD"
ElseIf (Worksheets("File").Range("x2").Value Like "*;ProductSubType:'SWLEG'*") Then
    Worksheets("File").Range("D2:D17783").Value = "XSW" 
End If 

answered Sep 29, 2017 at 17:45

Scott Craner's user avatar

Scott CranerScott Craner

146k9 gold badges47 silver badges80 bronze badges

5

Try using column X to set the extents of the values to fill in column D.

with worksheets("file")
    select case true
        case .cells(2, "X").value2 like "*ProductType:'FXD';*"
            .range(.cells(2, "D"), .cells(.cells(.rows.count, "X").end(xlup).row, "D")) = "FXD"
        case .cells(2, "X").value2 like "*;ProductSubType:'SWLEG'*"
            .range(.cells(2, "D"), .cells(.cells(.rows.count, "X").end(xlup).row, "D")) = "XSW"
        case else
            'do nothing
    end select
end with

answered Sep 29, 2017 at 18:07

1

Try changing
Selection.AutoFill Destination:=src.Columns("D") to
Selection.AutoFill Destination:=src.Columns("D:D")

This is going to drag that formula all the way down column D, which is what I assumed you’re trying to do, however, it will literally go down to row 1048576, so unless you’re trying to do that, change the second range to D & whatevervaluehere

answered Sep 29, 2017 at 17:43

dwirony's user avatar

dwironydwirony

5,5753 gold badges21 silver badges43 bronze badges

3

The IF function runs a logical test and returns one value for a TRUE result, and another value for a FALSE result. The result from IF can be a value, a cell reference, or even another formula. By combining the IF function with other logical functions like AND and OR, you can test more than one condition at a time.

Syntax

The generic syntax for the IF function looks like this:

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

The first argument, logical_test, is typically an expression that returns either TRUE or FALSE. The second argument, value_if_true, is the value to return when logical_test is TRUE. The last argument, value_if_false, is the value to return when logical_test is FALSE. Both value_if_true and value_if_false are optional, but you must provide one or the other. For example, if cell A1 contains 80, then:

=IF(A1>75,TRUE) // returns TRUE
=IF(A1>75,"OK") // returns "OK"
=IF(A1>85,"OK") // returns FALSE
=IF(A1>75,10,0) // returns 10
=IF(A1>85,10,0) // returns 0
=IF(A1>75,"Yes","No") // returns "Yes"
=IF(A1>85,"Yes","No") // returns "No"

Notice that text values like «OK», «Yes», «No», etc. must be enclosed in double quotes («»). However, numeric values should not be enclosed in quotes.

Logical tests

The IF function supports logical operators (>,<,<>,=) when creating logical tests. Most commonly, the logical_test in IF is a complete logical expression that will evaluate to TRUE or FALSE. The table below shows some common examples:

Goal Logical test
If A1 is greater than 75 A1>75
If A1 equals 100 A1=100
If A1 is less than or equal to 100 A1<=100
If A1 equals «Red» A1=»red»
If A1 is not equal to «Red» A1<>»red»
If A1 is less than B1 A1<B1
If A1 is empty A1=»»
If A1 is not empty A1<>»»
If A1 is less than current date A1<TODAY()

Notice text values must be enclosed in double quotes («»), but numbers do not. The IF function does not support wildcards, but you can combine IF with COUNTIF to get basic wildcard functionality. To test for substrings in a cell, you can use the IF function with the SEARCH function.

Pass or Fail example

In the worksheet shown above, we want to assign either «Pass» or «Fail» based on a test score. A passing score is 70 or higher. The formula in D6, copied down, is:

=IF(C5>=70,"Pass","Fail")

Translation: If the value in C5 is greater than or equal to 70, return «Pass». Otherwise, return «Fail».

Note that the logical flow of this formula can be reversed. This formula returns the same result:

=IF(C5<70,"Fail","Pass")

Translation: If the value in C5 is less than 70, return «Fail». Otherwise, return «Pass».

Both formulas above, when copied down, will return correct results.

Note: If you are new to the idea of formula criteria, this article explains many examples.

Assign points based on color

In the worksheet below, we want to assign points based on the color in column B. If the color is «red», the result should be 100. If the color is «blue», the result should be 125. This requires that we use a formula based on two IF functions, one nested inside the other. The formula in C5, copied down, is:

=IF(B5="red",100,IF(B5="blue",125))

Translation: IF the value in B5 is «red», return 100. Else, if the value in B5 is «blue», return 125.

Assign points based on color with the IF function

There are three things to notice in this example:

  1. The formula will return FALSE if the value in B5 is anything except «red» or «blue»
  2. The text values «red» and «blue» must be enclosed in double quotes («»)
  3. The IF function is not case-sensitive and will match «red», «Red», «RED», or «rEd».

This is a simple example of a nested IFs formula. See below for a more complex example.

Return another formula

The IF function can return another formula as a result. For example, the formula below will return A1*5% when A1 is less than 100, and A1*7% when A1 is greater than or equal to 100:

=IF(A1<100,A1*5%,A1*7%)

Nested IF statements

The IF function can be «nested». A «nested IF» refers to a formula where at least one IF function is nested inside another in order to test for more conditions and return more possible results. Each IF statement needs to be carefully «nested» inside another so that the logic is correct. For example, the following formula can be used to assign a grade rather than a pass / fail result:

=IF(C6<70,"F",IF(C6<75,"D",IF(C6<85,"C",IF(C6<95,"B","A"))))

Up to 64 IF functions can be nested. However, in general, you should consider other functions, like VLOOKUP or XLOOKUP for more complex scenarios, because they can handle more conditions in a more streamlined fashion. For a more details see this article on nested IFs.

Note: the newer IFS function is designed to handle multiple conditions without nesting. However, a lookup function like VLOOKUP or XLOOKUP is usually a better approach unless the logic for each condition is custom.

IF with AND, OR, NOT

The IF function can be combined with the AND function and the OR function. For example, to return «OK» when A1 is between 7 and 10, you can use a formula like this:

=IF(AND(A1>7,A1<10),"OK","")

Translation: if A1 is greater than 7 and less than 10, return «OK». Otherwise, return nothing («»).

To return B1+10 when A1 is «red» or «blue» you can use the OR function like this:

=IF(OR(A1="red",A1="blue"),B1+10,B1)

Translation: if A1 is red or blue, return B1+10, otherwise return B1.

=IF(NOT(A1="red"),B1+10,B1)

Translation: if A1 is NOT red, return B1+10, otherwise return B1.

IF cell contains specific text

Because the IF function does not support wildcards, it is not obvious how to configure IF to check for a specific substring in a cell. A common approach is to combine the ISNUMBER function and the SEARCH function to create a logical test like this:

=ISNUMBER(SEARCH(substring,A1)) // returns TRUE or FALSE

For example, to check for the substring «xyz» in cell A1, you can use a formula like this:

=IF(ISNUMBER(SEARCH("xyz",A1)),"Yes","No")

Read a detailed explanation here.

More information

  • Read more about nested IFs
  • Learn how to use VLOOKUP instead of nested IFs (video)
  • 50 Examples of formula criteria

Notes

  • The IF function is not case-sensitive.
  • To count values conditionally, use the COUNTIF or the COUNTIFS functions.
  • To sum values conditionally, use the SUMIF or the SUMIFS functions.
  • If any of the arguments to IF are supplied as arrays, the IF function will evaluate every element of the array.

Функция ЕСЛИ в Excel — это отличный инструмент для проверки условий на ИСТИНУ или ЛОЖЬ. Если значения ваших расчетов равны заданным параметрам функции как ИСТИНА, то она возвращает одно значение, если ЛОЖЬ, то другое.

Содержание

  1. Что возвращает функция
  2. Синтаксис
  3. Аргументы функции
  4. Дополнительная информация
  5. Функция Если в Excel примеры с несколькими условиями
  6. Пример 1. Проверяем простое числовое условие с помощью функции IF (ЕСЛИ)
  7. Пример 2. Использование вложенной функции IF (ЕСЛИ) для проверки условия выражения
  8. Пример 3. Вычисляем сумму комиссии с продаж с помощью функции IF (ЕСЛИ) в Excel
  9. Пример 4. Используем логические операторы (AND/OR) (И/ИЛИ) в функции IF (ЕСЛИ) в Excel
  10. Пример 5. Преобразуем ошибки в значения “0” с помощью функции IF (ЕСЛИ)

Что возвращает функция

Заданное вами значение при выполнении двух условий ИСТИНА или ЛОЖЬ.

Синтаксис

=IF(logical_test, [value_if_true], [value_if_false]) — английская версия

=ЕСЛИ(лог_выражение; [значение_если_истина]; [значение_если_ложь]) — русская версия

Аргументы функции

  • logical_test (лог_выражение) — это условие, которое вы хотите протестировать. Этот аргумент функции должен быть логичным и определяемым как ЛОЖЬ или ИСТИНА. Аргументом может быть как статичное значение, так и результат функции, вычисления;
  • [value_if_true] ([значение_если_истина]) — (не обязательно) — это то значение, которое возвращает функция. Оно будет отображено в случае, если значение которое вы тестируете соответствует условию ИСТИНА;
  • [value_if_false] ([значение_если_ложь]) — (не обязательно) — это то значение, которое возвращает функция. Оно будет отображено в случае, если условие, которое вы тестируете соответствует условию ЛОЖЬ.

Дополнительная информация

  • В функции ЕСЛИ может быть протестировано 64 условий за один раз;
  • Если какой-либо из аргументов функции является массивом — оценивается каждый элемент массива;
  • Если вы не укажете условие аргумента FALSE (ЛОЖЬ) value_if_false (значение_если_ложь) в функции, т.е. после аргумента value_if_true (значение_если_истина) есть только запятая (точка с запятой), функция вернет значение “0”, если результат вычисления функции будет равен FALSE (ЛОЖЬ).
    На примере ниже, формула =IF(A1> 20,”Разрешить”) или =ЕСЛИ(A1>20;»Разрешить») , где value_if_false (значение_если_ложь) не указано, однако аргумент value_if_true (значение_если_истина) по-прежнему следует через запятую. Функция вернет “0” всякий раз, когда проверяемое условие не будет соответствовать условиям TRUE (ИСТИНА).

    IF-EXCEL-01|
  • Если вы не укажете условие аргумента TRUE(ИСТИНА) (value_if_true (значение_если_истина)) в функции, т.е. условие указано только для аргумента value_if_false (значение_если_ложь), то формула вернет значение “0”, если результат вычисления функции будет равен TRUE (ИСТИНА);
    На примере ниже формула равна =IF (A1>20;«Отказать») или =ЕСЛИ(A1>20;»Отказать»), где аргумент value_if_true (значение_если_истина) не указан, формула будет возвращать “0” всякий раз, когда условие соответствует TRUE (ИСТИНА).

IF EXCEL - 02

Функция Если в Excel примеры с несколькими условиями

Пример 1. Проверяем простое числовое условие с помощью функции IF (ЕСЛИ)

При использовании функции ЕСЛИ в Excel, вы можете использовать различные операторы для проверки состояния. Вот список операторов, которые вы можете использовать:

IF-EXCEL-03

Ниже приведен простой пример использования функции при расчете оценок студентов. Если сумма баллов больше или равна «35», то формула возвращает “Сдал”, иначе возвращается “Не сдал”.

Excel-IF-04

Пример 2. Использование вложенной функции IF (ЕСЛИ) для проверки условия выражения

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

В приведенном ниже примере мы проверяем два условия.

  • Первое условие проверяет, сумму баллов не меньше ли она чем 35 баллов. Если это ИСТИНА, то функция вернет “Не сдал”;
  • В случае, если первое условие — ЛОЖЬ, и сумма баллов больше 35, то функция проверяет второе условие. В случае если сумма баллов больше или равна 75. Если это правда, то функция возвращает значение “Отлично”, в других случаях функция возвращает “Сдал”.

Excel-If-06

Пример 3. Вычисляем сумму комиссии с продаж с помощью функции IF (ЕСЛИ) в Excel

Функция позволяет выполнять вычисления с числами. Хороший пример использования — расчет комиссии продаж для торгового представителя.

В приведенном ниже примере, торговый представитель по продажам:

  • не получает комиссионных, если объем продаж меньше 50 тыс;
  • получает комиссию в размере 2%, если продажи между 50-100 тыс
  • получает 4% комиссионных, если объем продаж превышает 100 тыс.

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

=IF(B2<50,0,IF(B2<100,B2*2%,B2*4%)) — английская версия

=ЕСЛИ(B2<50;0;ЕСЛИ(B2<100;B2*2%;B2*4%)) — русская версия

Excel-IF-07

В формуле, использованной в примере выше, вычисление суммы комиссионных выполняется в самой функции ЕСЛИ. Если объем продаж находится между 50-100K, то формула возвращает B2 * 2%, что составляет 2% комиссии в зависимости от объема продажи.

Telegram Logo Больше лайфхаков в нашем Telegram Подписаться

Пример 4. Используем логические операторы (AND/OR) (И/ИЛИ) в функции IF (ЕСЛИ) в Excel

Вы можете использовать логические операторы (AND/OR) (И/ИЛИ) внутри функции для одновременного тестирования нескольких условий.

Например, предположим, что вы должны выбрать студентов для стипендий, основываясь на оценках и посещаемости. В приведенном ниже примере учащийся имеет право на участие только в том случае, если он набрал более 80 баллов и имеет посещаемость более 80%.

Excel-If-09

Вы можете использовать функцию AND (И) вместе с функцией IF (ЕСЛИ), чтобы сначала проверить, выполняются ли оба эти условия или нет. Если условия соблюдены, функция возвращает “Имеет право”, в противном случае она возвращает “Не имеет право”.

Формула для этого расчета:

=IF(AND(B2>80,C2>80%),”Да”,”Нет”) — английская версия

=ЕСЛИ(И(B2>80;C2>80%);»Да»;»Нет») — русская версия

Excel-IF-10

Пример 5. Преобразуем ошибки в значения “0” с помощью функции IF (ЕСЛИ)

С помощью этой функции вы также можете убирать ячейки содержащие ошибки. Вы можете преобразовать значения ошибок в пробелы или нули или любое другое значение.

Формула для преобразования ошибок в ячейках следующая:

=IF(ISERROR(A1),0,A1) — английская версия

=ЕСЛИ(ЕОШИБКА(A1);0;A1) — русская версия

Формула возвращает “0”, в случае если в ячейке есть ошибка, иначе она возвращает значение ячейки.

ПРИМЕЧАНИЕ. Если вы используете Excel 2007 или версии после него, вы также можете использовать функцию IFERROR для этого.

Точно так же вы можете обрабатывать пустые ячейки. В случае пустых ячеек используйте функцию ISBLANK, на примере ниже:

=IF(ISBLANK(A1),0,A1) — английская версия

=ЕСЛИ(ЕПУСТО(A1);0;A1) — русская версия

EXCEL-IF-11

This is a step-by-step guide on how to use IF function in Excel. It shows you how to create a formula using the IF function, it includes several IF formula examples, an introduction on how to use nested IF formulas, and the exercise file I used when creating this tutorial.

The Excel IF function performs a logical test and returns one value when the condition is TRUE and another when the condition is FALSE.

How do you write an if-then formula in Excel? Well, the syntax for IF statements is the same in all Excel versions. This means that you can use any of the examples shown in this article in Excel for Microsoft 365 or Excel 2021, 2019, 2016, 2013, 2010, 2007, and 2003.

How to use IF function in Excel:

  1. Select the cell where you want to insert the IF formula. Using your mouse or keyboard, navigate to the cell where you want to insert your formula.
  2. Type =IF(
  3. Insert the condition that you want to check, followed by a comma (,). The first argument of the IF function is the logical_test. This is the condition that you want to validate. For example C6 > 70.
  4. Insert the value to display when the condition is TRUE, followed by a comma (,). The second argument of the IF function is value_if_true. Here, you can insert a nested formula or a simple message such as “YES”.
  5. Insert the value to display when the condition is FALSE. The last argument of the IF function is value_if_false. Just like the previous step, you can insert a nested formula or display a message such as “NO”. This can also be set as an empty string (“”), which will display a cell that looks blank.
  6. Type ) to close the function and press ENTER

The following video shows you exactly how to apply the six steps described above and create your first IF formula.

The syntax that shows how to create an IF function in Excel is explained below:
=IF(logical_test, [value_if_true], [value_if_false])

IF is a logical function and implies setting 3 arguments:
logical_test – The logical condition that you want to test. This will return either a TRUE or a FALSE value.
value_if_true – [optional] The value or formula which will be used when logical_test is TRUE.
value_if_false – [optional] The value or formula which will be used when logical_test is FALSE.

Please remember that while both value_if_true and value_if_false are optional, at least one of them needs to be supplied. Otherwise, your IF formula will simply return 0 (zero).

Where is the IF function in Excel? Since this is a logical function, you can find the IF function in the Formulas tab, Function Library section, under Logical.

Logical operators for IF function

The IF function is one of the most used Excel functions, and it allows you to return different values when the logical condition supplied is TRUE or FALSE. An Excel if-then formula can use the following logical operators:

Logical operators Definition Example
= equal to A1=B1
<> not equal to A1<>B1
> greater than A1>B1
>= greater than or equal to A1>=B1
< lower than A1<B1
<= lower than or equal to A1<=B1

The IF function doesn’t support wildcards.

Your first IF formula

The IF function runs a logical test and returns different values depending on whether the result is TRUE or FALSE. The result from IF can be a value, a cell reference, or even another formula.

Now let’s move on to some examples.

We’ll be evaluating exam grades. If the student obtained a score higher than or equal to 70, then we will return the message “Pass.” If the grade is lower than 70, then we will display “Fail.”

In this example, I have inserted the following formula in cell F9:
=IF(E9>=70, "Pass", "Fail")

The 3 arguments for this IF formula are:
logical_test: E9>=70
value_if_true: Pass is returned if E9>=70.
value_if_false: Fail is returned if E9<70.

How to use IF function in Excel

Please note that when you want to use text in your IF formulas (like a word or sentence), you need to wrap the text in quotes (e.g. “Fail”). The only exception is while using TRUE or FALSE, which are built-in functionalities that Excel recognizes automatically.

How to use the IF function in Excel with another function or formula

The beauty of the IF function is that it allows us to build complex financial models with lots of interdependencies. This includes using different formulas based on conditional logic.

In our next example, we will use the IF function to calculate a payment fee based on the value of the order. If the order value is higher than or equal to $1000, then it should calculate a payment fee of 1.00%. However, if the total order value is lower than $1000, then it should use 1.50%.

The formula in cell F31 is:
=IF(E31>=1000, E31*1%, E31*1.5%)

Writing an IF formula with another function

Now let’s look at an IF formula that is dependent on user input. If we select free shipping for the order, then the shipping fee will be set to zero. Otherwise, it will be calculated as 3% of the order value.

This is something really easy to achieve, but it will open up so many opportunities for you to use the IF function in the future.

IF with user input

How to use nested IF statements in Excel

Nesting more IF functions allows you to perform multiple comparisons and create more complex formulas. However, you can only nest up to 64 IF functions in Excel. If you ever reach this limit (I never did), I can guarantee that there is a better and more elegant solution using functions like VLOOKUP, SUMIF, or COUNTIFS.

In the next example, I wrote a formula with several nested IF functions to assign a grade to a list of students based on their test results.

=IF(E71<60, "F", IF(E71<70, "D", IF(E71<80, "C", IF(E71<90, "B", "A"))))

The order of the conditions is important. When the conditions overlap, Excel will retrieve the [value_if_true] argument from the first IF statement that returns TRUE. This is why the conditions from the formula above need to be inserted in the same order for the formula to work properly.

Nested IF statements in Excel

Note: If you are running Office 365, then you can also look at the new IFS function. This function runs multiple tests and returns the value corresponding to the first TRUE result. It’s a very useful alternative to nested IF formulas and makes your formulas much easier to understand by others. You can read more about IFS on Microsoft’s website.

How to use IF formula with OR function in Excel

OR allows you to supply alternative conditions to an IF statement. This opens up opportunities to create complex scenarios where certain behavior is triggered by multiple possible conditions.

Let’s look at an IF formula that calculates a 2.00% shipping fee when the total order value is higher than $1000 or when there are more than 5 items in the order.

The IF OR statement I’ve used in cell H106 is:
=IF(OR(G106>1000, F106>5), G106*2%, 0)

Using IF with OR function

The OR function evaluates if G106>1000 or if F106>5 and the formula returns TRUE when either or both conditions are fulfilled.

How to use IF formula with AND function in Excel

AND allows you to supply multiple criteria to an IF statement. Basically, the IF function returns TRUE if, and only if, all the conditions are met.

Working with our previous example, let’s apply the shipping fee only when the total order value is higher than $1000 and the order contains more than 5 items.

The IF AND statement I’ve used in cell H106 is:
=IF(AND(G128>1000, F128>5), G128*2%, 0)

Using IF with AND function

The AND function evaluates if G106>1000 and if F106>5 and returns TRUE when both conditions are fulfilled.

How to use IF function with VLOOKUP in Excel

VLOOKUP can be nested inside an IF formula to retrieve data when a condition is TRUE or FALSE. In the next example, I will show you how to calculate shipping fees based on a different table that contains the thresholds and percentages to be applied depending on the order value.

The formula I’ve used in cell F152:
=IF(G152="No", VLOOKUP(E152, $J$146:$K$152, 2, TRUE)*E152, 0)

IF function with VLOOKUP

The formula uses the following arguments:
logical_test: G152="No"
value_if_true: VLOOKUP(E152, $J$146:$K$152, 2, TRUE)*E152 is used to retrieve the corresponding shipping fee percentage when G152=”No”
value_if_false: 0 is returned if G152 is anything else than “No.” In our case, the alternative is selecting “Yes” from the drop-down list.

Note: One thing to remember is that I’ve used a VLOOKUP formula with an approximate match argument. This means that your data must be sorted in ascending order by lookup value (in our case, the Order amount).

In case you need additional help, please also read this article that explains step-by-step how to use VLOOKUP function in Excel.

What to do next?

IF is a versatile function that can be used in a wide range of scenarios. I use it daily, and I can’t imagine a world where Excel would lack this functionality.

Practice writing formulas using the IF function, and your spreadsheets will definitely get better and more complex. For example, why not look at another example using an IF function with 3 conditions? It will show you more examples of how to insert an if formula in Excel using nested IF statements and multiple conditions.

Let me know if you have questions on how to use IF function in Excel or if you need advice on how to nest multiple IF statements in your Excel project by leaving a comment below.

Понравилась статья? Поделить с друзьями:
  • If value is not in range excel vba
  • If trust is just a word
  • If true then vba excel
  • If true and false excel vba
  • If today function in excel