Find unique in excel

Filter for unique values or remove duplicate values

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

In Excel, there are several ways to filter for unique values—or remove duplicate values:

  • To filter for unique values, click Data > Sort & Filter > Advanced.
    The Sort & Filter group on the Data tab

  • To remove duplicate values, click Data > Data Tools > Remove Duplicates.
    Remove Duplicates

  • To highlight unique or duplicate values, use the Conditional Formatting command in the Style group on the Home tab.

Filtering for unique values and removing duplicate values are two similar tasks, since the objective is to present a list of unique values. There is a critical difference, however: When you filter for unique values, the duplicate values are only hidden temporarily. However, removing duplicate values means that you are permanently deleting duplicate values.

A duplicate value is one in which all values in at least one row are identical to all of the values in another row. A comparison of duplicate values depends on the what appears in the cell—not the underlying value stored in the cell. For example, if you have the same date value in different cells, one formatted as «3/8/2006» and the other as «Mar 8, 2006», the values are unique.

Check before removing duplicates: Before removing duplicate values, it’s a good idea to first try to filter on—or conditionally format on—unique values to confirm that you achieve the results you expect.

Follow these steps:

  1. Select the range of cells, or ensure that the active cell is in a table.

  2. Click Data > Advanced (in the Sort & Filter group).

    The Sort & Filter group on the Data tab

  3. In the Advanced Filter popup box, do one of the following:

To filter the range of cells or table in place:

  • Click Filter the list, in-place.

To copy the results of the filter to another location:

  • Click Copy to another location.

  • In the Copy to box, enter a cell reference.

  • Alternatively, click Collapse Dialog Button image to temporarily hide the popup window, select a cell on the worksheet, and then click Expand Button image .

  • Check the Unique records only, then click OK.

The unique values from the range will copy to the new location.

When you remove duplicate values, the only effect is on the values in the range of cells or table. Other values outside the range of cells or table will not change or move.  When duplicates are removed, the first occurrence of the value in the list is kept, but other identical values are deleted. 

Because you are permanently deleting data, it’s a good idea to copy the original range of cells or table to another worksheet or workbook before removing duplicate values.

Follow these steps:

  1. Select the range of cells, or ensure that the active cell is in a table.

  2. On the Data tab, click Remove Duplicates (in the Data Tools group).

    Remove Duplicates

  3. Do one or more of the following:

    • Under Columns, select one or more columns.

    • To quickly select all columns, click Select All.

    • To quickly clear all columns, click Unselect All.

      If the range of cells or table contains many columns and you want to only select a few columns, you may find it easier to click Unselect All, and then under Columns, select those columns.

      Note: Data will be removed from all columns, even if you don’t select all the columns at this step. For example, if you select Column1 and Column2, but not Column3, then the “key” used to find duplicates is the value of BOTH Column1 & Column2.  If a duplicate is found in those columns, then the entire row will be removed, including other columns in the table or range.

  4. Click OK, and a message will appear to indicate how many duplicate values were removed, or how many unique values remain. Click OK to dismiss this message.

  5. Undo the change by click Undo (or pressing Ctrl+Z on the keyboard).

Note: You cannot conditionally format fields in the Values area of a PivotTable report by unique or duplicate values.

Quick formatting

Follow these steps:

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Style group, click the small arrow for Conditional Formatting, and then click Highlight Cells Rules, and select Duplicate Values.
    Duplicate values

  3. Enter the values that you want to use, and then choose a format.

Advanced formatting

Follow these steps:

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Styles group, click the arrow for Conditional Formatting, and then click Manage Rules to display the Conditional Formatting Rules Manager popup window.
    Conditional Formatting menu with Manage Rules highlighted

  3. Do one of the following:

    • To add a conditional format, click New Rule to display the New Formatting Rule popup window.

    • To change a conditional format, begin by ensuring that the appropriate worksheet or table has been chosen in the Show formatting rules for list. If necessary, choose another range of cells by clicking Collapse Button image button in the Applies to popup window temporarily hide it. Choose a new range of cells on the worksheet, then expand the popup window again Button image . Select the rule, and then click Edit rule to display the Edit Formatting Rule popup window.

  4. Under Select a Rule Type, click Format only unique or duplicate values.

  5. In the Format all list of Edit the Rule Description, choose either unique or duplicate.

  6. Click Format to display the Format Cells popup window.

  7. Select the number, font, border, or fill format that you want to apply when the cell value satisfies the condition, and then click OK. You can choose more than one format. The formats that you select are displayed in the Preview panel.

In Excel for the web, you can remove duplicate values.

Remove duplicate values

When you remove duplicate values, the only effect is on the values in the range of cells or table. Other values outside the range of cells or table will not change or move. When duplicates are removed, the first occurrence of the value in the list is kept, but other identical values are deleted.

Important: You can always click Undo to get back your data after you have removed the duplicates. That being said, it’s a good idea to copy the original range of cells or table to another worksheet or workbook before removing duplicate values.

Follow these steps:

  1. Select the range of cells, or ensure that the active cell is in a table.

  2. On the Data tab, click Remove Duplicates .

  3. In the Remove Duplicates dialog box, unselect any columns where you don’t want to remove duplicate values.

    Note: Data will be removed from all columns, even if you don’t select all the columns at this step. For example, if you select Column1 and Column2, but not Column3, then the “key” used to find duplicates is the value of BOTH Column1 & Column2.  If a duplicate is found in Column1 and Column2, then the entire row will be removed, including data from Column3.

  4. Click OK, and a message will appear to indicate how many duplicate values were removed. Click OK to dismiss this message.

Note: If you want to get back your data, simply click Undo (or press Ctrl+Z on the keyboard).

Need more help?

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

See Also

Count unique values among duplicates

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.

Skip to content

Как найти и выделить уникальные значения в столбце

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

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

  • Уникальные значения – это элементы, которые появляются в наборе данных только один раз.
  • Различные  – это элементы, которые появляются хотя бы один раз, то есть неповторяющиеся и первые вхождения повторяющихся значений.

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

  • Как найти уникальные значения формулами.
  • Фильтр для уникальных данных.
  • Выделение цветом и условное форматирование.
  • Быстрый и простой способ — Duplicate Remover.

Как найти уникальные значения при помощи формул.

Самый простой способ сделать это – использовать функции ЕСЛИ и СЧЁТЕСЛИ. В зависимости от типа данных, которые вы хотите найти, может быть несколько вариантов формулы, как показано в следующих примерах.

Как найти уникальные значения в столбце.

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

Чтобы найти уникальные значения в Excel:

=ЕСЛИ(СЧЁТЕСЛИ($A$2:$A$10;  $A2)=1; «Уникальный»; «»)

Чтобы определить различные значения:

=ЕСЛИ(СЧЁТЕСЛИ($A$2:$A2;  $A2)=1; «Различный»; «»)

Во второй формуле есть только одно небольшое отличие во второй ссылке на ячейку, что, однако, имеет большое значение:

Совет. Если вы хотите найти уникальные значения между двумя столбцами , т.е. найти значения, которые присутствуют в одном столбце, но отсутствуют в другом, используйте формулу, описанную в статье Как сравнить 2 столбца на предмет различий.

Уникальные строки в таблице.

Аналогичным образом вы можете найти уникальные строки в таблице Excel на основе изучения записей не в одном, а в двух или более столбцах. В этом случае вам необходимо использовать СЧЁТЕСЛИМН вместо СЧЁТЕСЛИ для оценки значений (до 127 пар диапазон/критерий можно обработать в одной формуле).

Формула для получения уникальных строк:

=ЕСЛИ(СЧЁТЕСЛИМН($A$2:$A$10; $A2; $B$2:$B$10; $B2)=1; «Уникальная»; «»)

Формула для поиска различных строк:

=ЕСЛИ(СЧЁТЕСЛИМН($A$2:$A2; $A2; $B$2:$B2; $B2)=1; «Различная»; «»)

В нашем случае уникальная комбинация Имя+Фамилия встречается 2 раза. А всего в списке 6 человек, из которых трое дублируются.

Как найти уникальные записи с учетом регистра?

Если вы работаете с набором данных, где важен регистр букв, вам понадобится немного более сложная формула массива.

Поиск уникальных значений с учетом регистра :

{=ЕСЛИ(СУММ((—СОВПАД($A$2:$A$10;A2)))=1;»Уникальный»;»»)}

Поиск различных значений с учетом регистра :

{=ЕСЛИ(СУММ((—СОВПАД($A$2:$A2;$A2)))=1;»Различный»;»»)}

Поскольку обе они являются формулами массива, обязательно нажмите Ctrl + Shift + Enter, чтобы правильно их записать.

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

Фильтр для уникальных значений.

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

  1. Примените одну из приведенных выше формул для определения уникальных или различных ячеек или строк.
  2. Выберите диапазон и нажмите кнопку «Фильтр» на вкладке «Данные». 
  3. Щелкните стрелку фильтрации в заголовке столбца, содержащего формулу, и выберите то, что хотите просмотреть:

Как выбрать уникальные из фильтра.

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

Чтобы быстро выбрать весь получившийся список, включая заголовки столбцов, отфильтруйте уникальные значения, щелкните любую ячейку в получившемся списке, а затем нажмите Ctrl + A.

Чтобы выбрать уникальные значения без заголовков столбцов, отфильтруйте их, выберите первую ячейку с данными и нажмите Ctrl + Shift + End, чтобы расширить выделение до последней ячейки.

Примечание. В некоторых редких случаях, в основном в очень больших книгах, рекомендованные выше комбинации клавиш могут выбирать как видимые, так и невидимые ячейки. Чтобы исправить это, нажмите сначала либо Ctrl + A или же Ctrl + Shift + End, а затем нажмите Alt +;  для выбора только видимых ячеек, игнорируя скрытые строки.

Если вам сложно запомнить такое количество комбинаций, используйте этот визуальный способ: выделите весь список, затем перейдите на вкладку «Главная» > «Найти и выделить» > «Выделить группу ячеек» и выберите «Только видимые ячейки».

Как скопировать уникальные значения в другое место?

Чтобы скопировать список на новое место, сделайте следующее:

  • Выберите отфильтрованные значения с помощью мыши или вышеупомянутых комбинаций клавиш.
  • Нажмите Ctrl + C для копирования выбранных значений.
  • Выберите верхнюю левую ячейку в целевом диапазоне (она может находиться на том же или другом листе) и нажмите Ctrl + V , чтобы вставить данные.

Выделение цветом уникальных значений в столбце.

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

Самый быстрый и простой способ выделить уникальные значения в Excel — применить встроенное правило условного форматирования:

  1. Выберите столбец данных, в котором вы хотите выделить уникальные.
  2. На вкладке Главная в группе Стили щелкните Условное форматирование > Правила выделения ячеек > Повторяющиеся значения …

  1. В диалоговом окне « Повторяющиеся значения » выберите «Уникальный» в левом поле и выберите желаемое форматирование в правом поле, затем нажмите « ОК» .

Совет. Если вас не устраивает какой-либо из предопределенных форматов, щелкните «Пользовательский формат …» (последний элемент в раскрывающемся списке) и установите цвет заливки и / или шрифта по своему вкусу.

Как видите, выделение уникальных значений в Excel — самая простая задача, которую можно себе представить. Однако встроенное правило Excel работает только для элементов, которые появляются в списке только один раз. Если вам нужно выделить различные значения — уникальные и первые вхождения дубликатов — то придется создать собственное правило на основе формулы. 

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

Как создать правило для условного форматирования уникальных значений?

Чтобы выделить уникальные или различные значения в столбце, выберите диапазон ячеек без заголовка столбца (вы же не хотите, чтобы заголовок выделялся, не так ли?) Затем создайте правило условного форматирования с помощью формулы.

Чтобы создать правило условного форматирования на основе формулы, выполните следующие действия:

  1. Перейдите на вкладку «Главная » и щелкните « Условное форматирование» > « Новое правило» > «Использовать формулу», чтобы с ее помощью определить, какие ячейки нужно форматировать .
  2. Введите формулу в поле «Форматировать значения …».
  3. Нажмите кнопку «Формат …» и выберите нужный цвет заливки и/или цвет шрифта.
  4. Наконец, нажмите кнопку ОК , чтобы применить правило.

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

Выделяем цветом отдельные уникальные значения.

Чтобы выделить значения, которые появляются в списке только один раз, используйте следующую формулу:

=СЧЁТЕСЛИ($A$2:$A$10;$A2)=1

Где A2 — первая, а A10 — последняя ячейка диапазона.

Чтобы выделить все различные значения в столбце, то есть встречающиеся хотя бы однажды, используйте это выражение:

= СЧЁТЕСЛИ($A$2:$A2;$A2)=1

Где A2 — самая верхняя ячейка диапазона.

Как выделить строку с уникальным значением в одном столбце.

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

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

Как видите, формула

=СЧЁТЕСЛИ($A$2:$A$10;$A2)=1

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

А можно использовать и такое выражение:

=СУММ(Ч($A2&$B2=$A$2:$A$10&$B$2:$B$10))<2

Результат будет таким же.

Как выделить уникальные строки?

Если вы хотите выделить строки на основе значений в двух или более столбцах, используйте функцию СЧЁТЕСЛИМН, которая позволяет указать несколько критериев в одной формуле.

Чтобы выделить уникальные строки:

=СЧЁТЕСЛИМН($A$2:$A$10;$A2; $B$2:$B$10;$B2)=1

Чтобы выделить различные строки:

=СЧЁТЕСЛИМН($A$2:$A2;$A2; $B$2:$B2;$B2)=1

Быстрый и простой способ найти и выделить уникальные значения

Как вы только что видели, Microsoft Excel предоставляет довольно много полезных функций, которые могут помочь вам идентифицировать и выделять уникальные значения на ваших листах. 

Однако все эти решения сложно назвать интуитивно понятными и простыми в использовании, поскольку они требуют запоминания нескольких различных формул. Конечно, для профессионалов Excel в этом нет ничего страшного :)

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

В этом последнем разделе нашего сегодняшнего руководства мы собираемся использовать надстройку Duplicate Remover  для Excel. Пожалуйста, пусть вас не смущает название инструмента. Помимо повторяющихся записей, он может отлично обрабатывать уникальные и различные записи.

Давайте посмотрим.

  1. Выберите любую ячейку в таблице, в которой вы хотите найти уникальные значения, и нажмите кнопку DuplicateRemover на вкладке AblebitsData в группе Dedupe.

Мастер запустится, и вся таблица будет выбрана автоматически. Итак, просто нажмите « Далее», чтобы перейти к следующему шагу.

  1. В зависимости от вашей цели выберите один из следующих вариантов и нажмите Далее :
    • Уникальные
    • Уникальные + 1е вхождения (различные)

  1. Выберите один или несколько столбцов, в которых вы хотите проверить значения.
    В этом примере мы хотим найти уникальные сочетания Заказчик + Товар на основе значений в двух столбцах. Их и выбираем при помощи галочки.
  2. Выберите один или несколько столбцов, в которых вы хотите проверить значения.

Если у вашей таблицы есть заголовки, обязательно установите флажок Mytable has headers. И если в вашей таблице могут встретиться пустые ячейки, то убедитесь, что установлен флажок Skipempty cells. Оба параметра находятся в верхней части диалогового окна и обычно выбираются по умолчанию.

Если вдруг в наших записях случайно появились лишние пробелы, то, думаю, стоит их игнорировать. Поэтому отмечаем также Ignore extra spaces.

Также наш поиск буден нечувствителен к регистру, то есть не будем при сравнении данных различать прописные и строчные буквы. Поэтому не активируем опцию Case-sensitive match.

  1. Выберите одно из следующих действий, которые нужно выполнить с найденными значениями:
    • Выделить цветом.
    • Выбрать и выделить.
    • Отметить в колонке статуса.
    • Копировать в другое место.

Если вы выберете опцию Select values, то все найденные значения окажутся выделенными, как будто вы кликали на них мышкой при нажатой клавише Ctrl. Пока они выделены, вы можете изменить их цвет фона и шрифта, границы и т.д. К сожалению, скопировать либо переместить их никуда не получится, так как такую операцию не поддерживает Excel.

В нашем случае чтобы найти уникальные значения, вполне достаточно будет просто выделить их цветом. Поэтому выберем Highlight with color.

Нажмите кнопку «Готово» и получите результат:

Вот как вы можете находить, выбирать и выделять уникальные значения в Excel с помощью надстройки Duplicate Remover. Это действительно просто, не правда ли?

Я рекомендую вам загрузить полнофункциональную ознакомительную версию Ultimate Suite и попробовать в работе Duplicate Remover и множество других инструментов, которые помогут сэкономить вам кучу времени при работе в Excel.

Extract Unique Values | Filter for Unique Values | Unique Function | Remove Duplicates

To find unique values in Excel, use the Advanced Filter. You can extract unique values or filter for unique values. If you have Excel 365 or Excel 2021, use the magic UNIQUE function.

Extract Unique Values

When using the Advanced Filter in Excel, always enter a text label at the top of each column of data.

1. Click a cell in the list range.

Vertical List

2. On the Data tab, in the Sort & Filter group, click Advanced.

Click Advanced

The Advanced Filter dialog box appears.

3. Click Copy to another location (see image below).

4. Click in the Copy to box and select cell C1.

5. Check Unique records only.

6. Click OK.

Unique Records Only

Result:

Extract Unique Values in Excel

Note: Excel removes all duplicate values (Lion in cell A7 and Elephant in cell A9) and sends the unique values to column C. You can also use this tool to extract unique rows in Excel.

Filter for Unique Values

Filtering for unique values in Excel is a piece of cake.

1. Click a cell in the list range.

Vertical List

2. On the Data tab, in the Sort & Filter group, click Advanced.

Click Advanced

3. Click Filter the list, in-place (see image below).

4. Check Unique records only.

5. Click OK.

Filter the List, in-place

Result:

Filter for Unique Values in Excel

Note: rows 7 and 9 are hidden. To clear this filter, on the Data tab, in the Sort & Filter group, click Clear. You can also use this tool to filter for unique rows in Excel.

Unique Function

If you have Excel 365 or Excel 2021, simply use the magic UNIQUE function to extract unique values.

1. The UNIQUE function below (with no extra arguments) extracts unique values.

UNIQUE function in Excel

Note: this dynamic array function, entered into cell C1, fills multiple cells. Wow! This behavior in Excel 365/2021 is called spilling.

2. The UNIQUE function below extracts values that occur exactly once.

Values that Occur Exactly Once

Note: the UNIQUE function has 2 optional arguments. The default value of 0 (second argument) tells the UNIQUE function to extract values from a vertical array. The value 1 (third argument) tells the UNIQUE function to extract values that occur exactly once.

Remove Duplicates

To find unique values (or unique rows) and delete duplicate values (or duplicate rows) at the same time, use the Remove Duplicates tool in Excel.

On the Data tab, in the Data Tools group, click Remove Duplicates.

Click Remove Duplicates

In the example below, Excel removes all identical rows (blue) except for the first identical row found (yellow).

Remove Duplicates Example Remove Duplicates Result

Note: visit our page about removing duplicates to learn more about this great Excel tool.

This tutorial describes multiple ways to extract a unique or distinct list from a column in Excel. This post also covers a method to remove duplicates from a range. It’s one of the most common data crunching task in Excel.

Scenario

Suppose you have a list of customer names. The list has some duplicate values. You wish to extract unique values from it. Unique values would be a distinct list. To make it more clear, unique values are the values that appear in a column only once.

Sample File

Click on the link below and download the excel file for reference. We will use this workbook to demonstrate methods to find unique values from a column.

Extract unique values from a column

The dataset contains 13 records. Data starts from cell B3 and ends with cell B15. Header of the list exists in cell B2.

LIST1
Jhonson
Jhonson
Jhonson
Dave
Dave
Deepanshu
Sohan
Neha
Deepanshu
Neha
Deepanshu
Neha
Sohan



See the snapshot of actual data in images below.

4 Methods to Extract Unique Values

  1. Advanced Filter
  2. Index- Match Array Formula
  3. Excel Macro (VBA)
  4. Remove Duplicates

The above methods are explained in detail in the following sections.

Solutions

1. Advanced Filter

Follow the steps shown in the animation below

Steps to extract unique values using Advanced Filter

  1. Go to Data tab in the menu
  2. In Sort and Filter box, Click Advanced button 
  3. Choose «Copy to another location»
  4. In «List range :» box, select a range from which unique values need to be extracted (including header)
  5. In «Copy to :» box, select a range in which final output to be put
  6. Check Unique records only
  7. Click Ok

2. INDEX-MATCH (Array Formula)

Extract Unique Values — Formula

FORMULA 

=IFERROR(INDEX($B$3:$B$15, MATCH(0,COUNTIF($D$2:D2, $B$3:$B$15), 0)),»»)


Hit CTRL+ SHIFT + ENTER to confirm this formula as it’s an array formula. If done correctly, Excel will automatically place curly braces {…} around the formula.

After placing curly braces, the above formula would look like this :

{=IFERROR(INDEX($B$3:$B$15, MATCH(0,COUNTIF($D$2:D2, $B$3:$B$15), 0)),»»)}

Copy the above formula and paste it into cell D3. And paste it down till the cell D12 (Select the range D3:D12 and press Ctrl+D).

HOW TO USE

The functioning of this method is visible in the animated image below.

Version 2 : IF BLANK VALUES IN A LIST

Suppose there are missing or blank values in your list from which you want to extract unique values. In this case, you need to tweak your formula. The modified formula is explained below —

Extract Unique Values given blank values

FORMULA

=IFERROR(INDEX($B$3:$B$15, MATCH(0,IF(ISBLANK($B$3:$B$15),1,COUNTIF($D$2:D2, $B$3:$B$15)), 0)),»»)


Copy the above formula and paste it into cell D3. And paste it down till the cell D12 (Shortcut key : Ctrl+D).

You need to press CTRL+ SHIFT + ENTER  to submit this formula. It is different than the standard ENTER button to enter a formula. If you do it right, MS Excel will put curly braces {…} around the formula. It would view like this :

{=IFERROR(INDEX($B$3:$B$15, MATCH(0,IF(ISBLANK($B$3:$B$15),1,COUNTIF($D$2:D2, $B$3:$B$15)), 0)),»»)}

How this formula works

First we need to understand the meaning and use of array formula.

Array formula allows you to process a certain operation on multiple values using a single function. In other words, we can perform some calculation on more than one value without doing it manually on each cell. For example, you want to multiply each value by 5 and then sum all of the returned values.from multiplication. Suppose following values are stored in cell A1:A3

25
35
45

Enter the formula  =SUM(A1:A3*5) with CTRL+SHIFT+ENTER. It returns 525. In this case, it is doing matrix multiplication and then adds all the numbers.

Functioning of Formula : Step by Step

Step 1 : COUNTIF($D$2:D2, $B$3:$B$15)


Syntax :
COUNTIF(range, condition)
It counts the number of cells within a range that meet the given condition

COUNTIF($D$2:D2, $B$3:$B$15) returns 1 if $D$2:D2 is found in $B$3:$B$15 else 0.

For example, for the second distinct record Dave, the formula becomes COUNTIF($D$2:D3, $B$3:$B$15). It is searching values D2 and D3 in the range B3:B15. The array becomes 

={1;1;1;0;0;0;0;0;0;0;0;0;0}. It is 1 when values of D2 and D3 are found and 0 where it is not found.

Step 2 : In this step, we are checking the position of item that has an array value 0 in Step I.

Syntax : MATCH(lookup_value;lookup_array; [match_type] 

It gives the relative position of an item in an array that matches a specified value.

MATCH(0,COUNTIF($D$2:D2, $B$3:$B$15), 0) returns 4 for the second distinct value. It is 4 because the value Dave is placed in the fourth position of the list. [Also see 0 is the fourth value of the step 1 array — {1;1;1;0;0;0;0;0;0;0;0;0;0}]

Step 3 : In this step, we extract the desired distinct value. The INDEX function helps to achieve it.

Syntax : INDEX(array,row_num,[column_num])

The INDEX function returns the reference of cell meeting row and column number in a given range.

INDEX($B$3:$B$15, MATCH(0,COUNTIF($D$2:D2, $B$3:$B$15), 0)) returns Dave.



Tutorial : Excel Array Formula with Examples

3. MACRO (Advanced Filter)

It’s an excel macro to find distinct values from a column in Excel. In this method, we are using the same logic as we have done in first method i.e. Advanced filter. Here, we are applying advanced filter via excel macro rather than doing it manually.


VBA CODE

How to create unique list using macro

1. Go to excel sheet where data exists.
2. Press Alt + F11 to open VB editor window

3. Go to Insert menu >> Module. It will create a module.

4. In the module, copy and paste the above vba code into the window
5. Close VB Editor Window
6. Go back to your sheet
7. Press Alt + F8. Select CreateUniqueList under Macro name box and Hit Run button.

Download the workbook



Customise Macro Code

The following are two most frequently asked questions about above excel macro with solutions. If you have any other question regarding the macro, post your question on comment box below.

Q. How to paste unique values to another existing worksheet?

Change ActiveSheet.Range(«D2») to Sheets(«newsheet»).Range(«D2»)

In the above code, change «newsheet» to the name of the existing sheet wherein you want to paste unique values.


Q. How to paste unique values in a new worksheet?

Use the program below. It will paste distinct values to a new worksheet named «mysheet». You can change it to any name you want —

Option Explicit
Sub CreateUniqueList()
Dim lastrow As Long
Dim ws As String
ws = ActiveSheet.Name
lastrow = Cells(Rows.Count, «B»).End(xlUp).Row
Sheets.Add.Name = «mysheet»
Sheets(ws).Range(«B2:B» & lastrow).AdvancedFilter _
    Action:=xlFilterCopy, _
    CopyToRange:=Sheets(«mysheet»).Range(«D2»), _
    UNIQUE:=True
End Sub

I have added one more way to extract unique values from a range [Updated : June 2016]

4. Remove Duplicates Option 

The most easiest way to extract unique values from a range is to use «Remove Duplicates» option. See the snapshot below —

Unique values : Remove Duplicates Option

Warning : If you want to keep your original data (not overwrite unique values), make a copy of it (Paste original data to another range or tab) Otherwise original data would be removed.


Steps to remove duplicates

Select range >> Go to Data option >> Click on Remove Duplicates >> Select the column that contains duplicates >> Ok

Important Note :

  1. If you have multiple columns in a range and you want to remove duplicates based on a single column, make sure only the column that contains duplicates is selected.
Remove Duplicates by a column

2. If you want to remove duplicates based on all the columns (whole row), make sure all the columns are selected.

Related Articles
1. Count Unique values in a column
2. Count Unique values in multiple columns
3. Select and Count Duplicate values in Excel

About Author:

Deepanshu founded ListenData with a simple objective — Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he has worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and Human Resource.

See all How-To Articles

This tutorial demonstrates how to find unique values in Excel and Google Sheets.

find unique values final data

Find Unique Values Using Advanced Filter

The first option to find and extract unique values in Excel is to use an advanced filter. Say you have the list of names, shown below, with duplicates.

find unique values initial data

To get a list of unique values (without duplicates) in Column C, follow these steps:

  1. Select any cell in the data range (B2, for example) and in the Ribbon, go to Data > Advanced.

find unique values advanced filter

  1. In the Advanced Filter window, (1) select Copy to another location. (2) In the Copy to box, enter the cell where you want the copied list of unique values to start (e.g., C1). Then (3) check Unique records only and (4) click OK.

Note that, while you can also filter a data range in-place by selecting the first Action, that would be practically the same as filtering duplicate values.

find unique values advanced filter 2

As a result, in Column C you get all unique values from Column B, without duplicates.

find unique values final data

You can also use VBA code to find unique values in Excel.

Find Unique Values Using the UNIQUE Function

You can also use the UNIQUE Function to achieve the same thing. This function extracts a list of unique values from a given range. To this, in cell C2, enter the formula:

=UNIQUE(B2:B13)

find unique values unique function

The result is the same as when you use an advanced filter: Unique values are copied in Column C.

See also: Using Find and Replace in Excel VBA

Find Unique Values in Google Sheets

There is no Advanced Filter in Google Sheets, but you can use the UNIQUE Function the same way in both Excel and Google Sheets.

unique values gs

Понравилась статья? Поделить с друзьями:
  • Find underlined text in word
  • Find twelve culture words in the word search 18
  • Find translation of the following words and word combinations in the text
  • Find tools in word
  • Find tool in word