Excel if concatenate string

This tutorial will demonstrate how to concatenate cell values based on criteria using the CONCAT Function in Excel and Google Sheets.

concatenate if Main Function

The CONCAT Function

Users of Excel 2019+ have access to the CONCAT Function which is used to join multiple strings into a single string.

Notes:

  • Our first example uses the CONCAT Function and so is not available to Excel users before Excel 2019. See a later section in this tutorial for how to replicate this example in older versions of Excel.
  • Google Sheets users also have access to the CONCAT Function, but unlike in Excel, it only allows two values or cell references to be joined together and does not allow inputs of cell ranges. See a later section on how this example can be achieved in Google Sheets by using the TEXTJOIN Function instead.

This example will use the CONCAT and IF Functions in an array formula to create a text string of Player Names which relate to a Team value of Red

=CONCAT(IF(C3:C8="Red",B3:B8,""

CONCAT IF

Users of Excel 2019 will need to enter this formula as an array function by pressing CTRL + SHIFT + ENTER. Users of later versions of Excel do not need to follow this step.

To explain what this formula is doing, lets break it down into steps:

This is our final formula:

=CONCAT(IF(C3:C8="Red",B3:B8,""

First, Excel reads the range values into the formula:

=CONCAT(IF({"Red"; "Blue"; "Blue"; "Red"; "Blue"; "Red"}="Red",{"A"; "B"; "C"; "D"; "E"; "F"},""

Next the list of Team names is compared to the value Red:

=CONCAT(IF({TRUE; FALSE; FALSE; TRUE; FALSE; TRUE},{"A"; "B"; "C"; "D"; "E"; "F"},""

The IF Function replaces TRUE values with the Player Name, and FALSE values with “”

=CONCAT({"A"; ""; ""; "D"; ""; "F"

The CONCAT Function then combines all of the array values into one text string:

="ADF"

Adding Delimiters or Ignoring Empty Values

If it is required to add delimiting values or text between each value, or for the function to ignore empty cell values, The TEXTJOIN Function can be used instead if you need to add delimiters

Read our TEXTJOIN If article to learn more.

Concatenate If – in pre-Excel 2019

As the CONCAT and TEXTJOIN Functions are not available before the Excel 2019 version, we need to solve this problem in a different way. The CONCATENATE Function is available but does not take ranges of cells as inputs or allow array operations and so we are required to use a helper column with an IF Function instead.

This next example shows how to use a helper column to create a text string of Player Names which relate to a Team value of Red:

=IF(C3="Red",B3,"" &D4

CONCATENATE Helper

The first step in this example is to use an IF Function to replicate the condition of Team = Red:

=IF(C3="Red",B3,""

CONCATENATE Helper 1

Next, we can create a column that builds up a list of these values into one cell by also referencing the cell below it:

=D3&E4

CONCATENATE Helper 2

This formula uses the & character to join two values together. Note that the CONCATENATE Function could be used to create exactly the same result, but the & method is often preferred as it is shorter and makes it clearer what action the formula is performing.

These two helper columns can then be combined into one formula:

=IF(C3="Red",B3,""&D4

CONCATENATE Helper

A summary cell can then reference the first value in the Player List helper column:

=D3

Concatenate If in Google Sheets

Google Sheets users should use the TEXTJOIN Function to concatenate values based on a condition.

This example will use the TEXTJOIN and IF Functions to create a text string of Player Names which relate to a Team value of Red

=ARRAYFORMULA(TEXTJOIN("",FALSE,IF(C3:C8="Red",B3:B8,"")))

concatenate if Google Function

As this formula requires array inputs for the cell ranges, the ARRAYFORMULA Function should be added to the formula by pressing CTRL + SHIFT + ENTER.

What I am trying to do is concatenate two cells, then check that concatenated value against a column of values, and put an X in a cell if such a value exists. The following equation is what I’m using:

{=IF(CONCATENATE(A2, " ", B2) = 'MasterList'!$C:$C, "x", "")}

Column A is the name of the software and Column B the version number (A="Microsoft .NET Framework 4.5.1", B="4.5.50938", for example). I know that this concatenated value exists on the MasterList worksheet so I don’t understand why I’m not getting the answer I expect.

Gurus, what’s my flaw here?

0m3r's user avatar

0m3r

12.2k15 gold badges33 silver badges70 bronze badges

asked Mar 29, 2017 at 22:24

Tchotchke's user avatar

The fastest comparison/lookup on the worksheet is a MATCH function. If you have a long column to put this formula into you could try,

=IF(ISNUMBER(MATCH(CONCATENATE(A2, " ", B2), 'MasterList'!$C:$C, 0)), "x", "")

Fill down as necessary.

answered Mar 29, 2017 at 23:04

1

It seams that you select the entire column C on yout MasterListSheet. Don’t you mean just one cell? Like:

=IF(CONCATENATE(A2, " ", B2) = 'MasterList'!$C1, "x", "")

or try to : =IF(CONCATENATE(A2, " ", B2) = MasterList.!$C1, "x", "") (on open Office)

Best thing is instead of you write the Sheet name, let Excel do it for you by editing the formula, remove the sheet name and then with a mouse click navigate to the desired area.

answered Mar 29, 2017 at 22:41

Alg_D's user avatar

Alg_DAlg_D

2,2026 gold badges29 silver badges62 bronze badges

I just want to say that before seeing this question, I had no idea what array formulas were.

I have the following working example:

Sheet1:

A1: Microsoft .NET Framework 4.5.1
B1: 4.5.50938

// press control-shift-enter after typing formula
C4: =IF(CONCATENATE(A1," ",B1)=Sheet2!$A:$A,"YAY","NAY")

Sheet2:

A1: Microsoft .NET Framework 4.5.1 4.5.50938

Not sure what the issue is with your spreadsheet. Do the values in MasterList!$C:$C actually correspond to what you expect as the result of the concatenation?

answered Mar 29, 2017 at 22:30

Forest Kunecke's user avatar

1

This is not a valid array formula. The LHS is a single cell while the RHS is an array. What it actually does is compare the concatenation to all cells of columns C in MasterList.

You either need to make it a valid array formula or a normal formula. I recommend the second solution.

For the first solution, it should be:

{=IF(CONCATENATE(A:A, " ",B:B ) ='MasterList'!$C:$C, "x", "")}

However, this will be very slow because it will compute and concatenate two full columns, and moreover you will have to select your whole range where you want to calculate it (a full columns) then press Ctrl+Shift+Enter.

You can make it a simple formula in on cell then copy/paste along your column. Formula for C2:

=IF(CONCATENATE(A2, " ", B2) = 'MasterList'!$C2, "x", "")

answered Mar 29, 2017 at 22:39

A.S.H's user avatar

A.S.HA.S.H

29k5 gold badges22 silver badges49 bronze badges

Склеивание текста по условию

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

Допустим, что у нас имеется база данных по клиентам, где одному названию компании может соответствовать несколько разных email’ов ее сотрудников. Наша задача состоит в том, чтобы собрать все адреса по названиям компаний и сцепить их (через запятую или точку с запятой), чтобы сделать потом, например, почтовую рассылку по клиентам, т.е. получить на выходе что-то похожее на:

склеивание (сцепка) текста по условию

Другими словами, нам нужен инструмент, который будет склеивать (сцеплять) текст по условию — аналог функции СУММЕСЛИ (SUMIF), но для текста.

Способ 0. Формулой

Не очень изящный, зато самый простой способ. Можно написать несложную формулу, которая будет проверять отличается ли компания в очередной строке от предыдущей.  Если не отличается, то приклеиваем через запятую очередной адрес. Если отличается, то «сбрасываем» накопленное, начиная заново:

Сцепка текста по условию формулой

Минусы такого подхода очевидны: из всех ячеек полученного дополнительного столбца нам нужны только последние по каждой компании (желтые). Если список большой, то чтобы их быстро отобрать придется добавить еще один столбец, использующий функцию ДЛСТР (LEN), проверяющий длину накопленных строк:

Отбор строк

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

Способ 1. Макрофункция склейки по одному условию

Если исходный список не отсортирован по компаниям, то приведенная выше простая формула не работает, но можно легко выкрутиться с помощью небольшой пользовательской функции на VBA. Откройте редактор Visual Basic нажатием на сочетание клавиш Alt+F11 или с помощью кнопки Visual Basic на вкладке Разработчик (Developer). В открывшемся окне вставьте новый пустой модуль через меню Insert — Module и скопируйте туда текст нашей функции:

Function MergeIf(TextRange As Range, SearchRange As Range, Condition As String)
    Dim Delimeter As String, i As Long
    Delimeter = ", " 'символы-разделители (можно заменить на пробел или ; и т.д.)
    
    'если диапазоны проверки и склеивания не равны друг другу - выходим с ошибкой
    If SearchRange.Count <> TextRange.Count Then
        MergeIf = CVErr(xlErrRef)
        Exit Function
    End If
    
    'проходим по все ячейкам, проверяем условие и собираем текст в переменную OutText
    For i = 1 To SearchRange.Cells.Count
        If SearchRange.Cells(i) Like Condition Then OutText = OutText & TextRange.Cells(i) & Delimeter
    Next i
    
    'выводим результаты без последнего разделителя
    MergeIf = Left(OutText, Len(OutText) - Len(Delimeter))
End Function

Если теперь вернуться в Microsoft Excel, то в списке функций (кнопка fx в строке формул или вкладка Формулы — Вставить функцию) можно будет найти нашу функцию MergeIf в категории Определенные пользователем (User Defined). Аргументы у функции следующие:

функция сцепить если выполняется условие

Способ 2. Сцепить текст по неточному условию

Если заменить в 13-й строчке нашего макроса первый знак = на оператор приблизительного совпадения Like, то можно будет осуществлять склейку по неточному совпадению исходных данных с критерием отбора. Например, если название компании может быть записано в разных вариантах, то мы можем одной функцией проверить и собрать их все:

склейка по приблизительному условию

Поддерживаются стандартные спецсимволы подстановки:

  • звездочка (*) — обозначает любое количество любых символов (в т.ч. и их отсутствие)
  • вопросительный знак (?) — обозначает один любой символ
  • решетка (#) — обозначает одну любую цифру (0-9)

По умолчанию оператор Like регистрочувствительный, т.е. понимает, например, «Орион» и «оРиОн» как разные компании. Чтобы не учитывать регистр можно добавить в самое начало модуля в редакторе Visual Basic строчку Option Compare Text, которая переключит Like в режим, когда он невосприимчив к регистру.

Таким образом можно составлять весьма сложные маски для проверки условий, например:

  • ?1##??777RUS — выборка по всем автомобильным номерам 777 региона, начинающимся с 1
  • ООО* — все компании, название которых начинается на ООО
  • ##7## — все товары с пятизначным цифровым кодом, где третья цифра 7
  • ????? — все названия из пяти букв и т.д.

Способ 3. Макрофункция склейки текста по двум условиям

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

Function MergeIfs(TextRange As Range, SearchRange1 As Range, Condition1 As String, SearchRange2 As Range, Condition2 As String)
    Dim Delimeter As String, i As Long
    Delimeter = ", " 'символы-разделители (можно заменить на пробел или ; и т.д.)
    
    'если диапазоны проверки и склеивания не равны друг другу - выходим с ошибкой
    If SearchRange1.Count <> TextRange.Count Or SearchRange2.Count <> TextRange.Count Then
        MergeIfs = CVErr(xlErrRef)
        Exit Function
    End If
    
    'проходим по все ячейкам, проверяем все условия и собираем текст в переменную OutText
    For i = 1 To SearchRange1.Cells.Count
        If SearchRange1.Cells(i) = Condition1 And SearchRange2.Cells(i) = Condition2 Then
            OutText = OutText & TextRange.Cells(i) & Delimeter
        End If
    Next i
    
    'выводим результаты без последнего разделителя
    MergeIfs = Left(OutText, Len(OutText) - Len(Delimeter))
End Function

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

склейка по нескольким условиям

Способ 4. Группировка и склейка в Power Query

Решить проблему можно и без программирования на VBA, если использовать бесплатную надстройку Power Query. Для Excel 2010-2013 ее можно скачать здесь, а в Excel 2016 она уже встроена по умолчанию. Последовательность действий будет следующей:

Power Query не умеет работать с обычными таблицами, поэтому первым шагом превратим нашу таблицу в «умную». Для этого ее нужно выделить и нажать сочетание Ctrl+T или выбрать на вкладке Главная — Форматировать как таблицу (Home — Format as Table). На появившейся затем вкладке Конструктор (Design) можно задать имя таблицы (я оставил стандартное Таблица1):

Умная таблица

Теперь загрузим нашу таблицу в надстройку Power Query. Для этого на вкладке Данные (если у вас Excel 2016) или на вкладке Power Query (если у вас Excel 2010-2013) жмем Из таблицы (Data — From Table):

Загрузка в Power Query

В открывшемся окне редактора запросов выделяем щелчком по заголовку столбец Компания и сверху жмем кнопку Группировать (Group By). Вводим имя нового столбца и тип операции в группировке — Все строки (All Rows):

Группировка в Power Query

Жмем ОК и получаем для каждой компании мини-таблицу сгруппированных значений. Содержимое таблиц хорошо видно, если щелкать левой кнопкой мыши в белый фон ячеек (не в текст!) в получившемся столбце:

Содержимое таблиц группировки

Теперь добавим еще один столбец, где с помощью функции склеим через запятую содержимое столбцов Адрес в каждой из мини-таблиц. Для этого на вкладке Добавить столбец жмем Пользовательский столбец (Add column — Custom column) и в появившемся окне вводим имя нового столбца и формулу сцепки на встроенном в Power Query языке М:

Пользовательский столбец с функцией склейки

Обратите внимание, что все М-функции регистрочувствительные (в отличие от Excel). После нажатия на ОК получаем новый столбец со склееными адресами:

Результат

Осталось удалить ненужный уже столбец ТаблАдресов (правой кнопкой мыши по заголовку — Удалить столбец) и выгрузить результаты на лист, нажав на вкладке Главная — Закрыть и загрузить (Home — Close and load):

Выгрузка результатов на лист

Важный нюанс: в отличие от предыдущих способов (функций), таблицы из Power Query не обновляются автоматически. Если в будущем произойдут какие-либо изменения в исходных данных, то нужно будет щелкнуть правой кнопкой в любое место таблицы результатов и выбрать команду Обновить (Refresh).

Ссылки по теме

  • Как разделить длинную текстовую строку на части
  • Несколько способов склеить текст из разных ячеек в одной
  • Использование оператора Like для проверки текста по маске

Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel 2010 Excel 2007 Excel for Mac 2011 Excel Starter 2010 More…Less

Use CONCATENATE, one of the text functions, to join two or more text strings into one string.

Important: In Excel 2016, Excel Mobile, and Excel for the web, this function has been replaced with the CONCAT function. Although the CONCATENATE function is still available for backward compatibility, you should consider using CONCAT from now on. This is because CONCATENATE may not be available in future versions of Excel.

Syntax: CONCATENATE(text1, [text2], …)

For example:

  • =CONCATENATE(«Stream population for «, A2, » «, A3, » is «, A4, «/mile.»)

  • =CONCATENATE(B2, » «,C2)

Argument name

Description

text1    (required)

The first item to join. The item can be a text value, number, or cell reference.

Text2, …    (optional)

Additional text items to join. You can have up to 255 items, up to a total of 8,192 characters.

Examples

To use these examples in Excel, copy the data in the table below, and paste it in cell A1 of a new worksheet.

Data

brook trout

Andreas

Hauser

species

Fourth

Pine

32

Formula

Description

=CONCATENATE(«Stream population for «, A2, » «, A3, » is «, A4, «/mile.»)

Creates a sentence by joining the data in column A with other text. The result is Stream population for brook trout species is 32/mile.

=CONCATENATE(B2, » «, C2)

Joins three things: the string in cell B2, a space character, and the value in cell C2. The result is Andreas Hauser.

=CONCATENATE(C2, «, «, B2)

Joins three things: the string in cell C2, a string with a comma and a space character, and the value in cell B2. The result is Andreas, Hauser.

=CONCATENATE(B3, » & «, C3)

Joins three things: the string in cell B3, a string consisting of a space with ampersand and another space, and the value in cell C3. The result is Fourth & Pine.

=B3 & » & » & C3

Joins the same items as the previous example, but by using the ampersand (&) calculation operator instead of the CONCATENATE function. The result is Fourth & Pine.

Common Problems

Problem

Description

Quotation marks appear in result string.

Use commas to separate adjoining text items. For example: Excel will display =CONCATENATE(«Hello «»World») as Hello»World with an extra quote mark because a comma between the text arguments was omitted.

Numbers don’t need to have quotation marks.

Words are jumbled together.

Without designated spaces between separate text entries, the text entries will run together. Add extra spaces as part of the CONCATENATE formula. There are two ways to do this:

  • Add double quotation marks with a space between them » «. For example: =CONCATENATE(«Hello», » «, «World!»).

  • Add a space after the Text argument. For example: =CONCATENATE(«Hello «, «World!»). The string «Hello » has an extra space added.

The #NAME? error appears instead of the expected result.

#NAME? usually means there are quotation marks missing from a Text argument.

Best practices

Do this

Description

Use the ampersand & character instead of the CONCATENATE function.

The ampersand (&) calculation operator lets you join text items without having to use a function.

For example, =A1 & B1 returns the same value as =CONCATENATE(A1,B1). In many cases, using the ampersand operator is quicker and simpler than using CONCATENATE to create strings.

Learn more about using operation calculators.

Use the TEXT function to combine and format strings.

The TEXT function converts a numeric value to text and combines numbers with text or symbols.

For example, if cell A1 contains the number 23.5, you can use the following formula to format the number as a dollar amount:

=TEXT(A1,»$0.00″)

Result: $23.50

Related

  • Use the TEXT function to combine and format strings.

  • Learn more about using operation calculators.

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.


The following examples show how to use a concatenate if formula in Excel.

Example 1: Concatenate If (By Column)

Suppose we have the following data in Excel:


We can use the following formula to concatenate cells in column A and B only if the value in column B is equal to “Good”:

=CONCAT(IF(B2="Good", A2:B2, ""))

The following screenshot shows how to use this formula in practice:

Concatenate if formula excel

If the cell in column B is equal to “Good” then the value in column C is equal to the concatenation of the cells in column A and B.

Otherwise, this formula simply returns a blank value.

Example 2: Concatenate If (By Row)

Once again suppose we have the following data in Excel:


We can use the following formula to concatenate all of the cells in column A where the value in column B is equal to “Good”:

=CONCAT(IF(B2:B7="Good", A2:A7, ""))

The following screenshot shows how to use this formula in practice:

Notice that the value in cell C2 is the result of concatenating every value in column A where the corresponding value in column B is equal to “Good.”

Note: You can find the complete documentation for the CONCAT function in Excel here.

Additional Resources

The following tutorials explain how to perform other common tasks in Excel:

Excel: How to Remove Specific Text from Cells
Excel: How to Delete Rows with Specific Text
Excel: How to Check if Cell Contains Partial Text
Excel: How to Check if Cell Contains Text from List

Понравилась статья? Поделить с друзьями:
  • Excel if color macro
  • Excel if check for text
  • Excel if check for error
  • Excel if character is a number
  • Excel if cells do not contain text