Excel find what row

Use LOOKUP, one of the lookup and reference functions, when you need to look in a single row or column and find a value from the same position in a second row or column.

For example, let’s say you know the part number for an auto part, but you don’t know the price. You can use the LOOKUP function to return the price in cell H2 when you enter the auto part number in cell H1.

An example of how you might use the LOOKUP function

Use the LOOKUP function to search one row or one column. In the above example, we’re searching prices in column D.

Tips: Consider one of the newer lookup functions, depending on which version you are using.

  • Use VLOOKUP to search one row or column, or to search multiple rows and columns (like a table). It’s a much improved version of LOOKUP. Watch this video about how to use VLOOKUP.

  • If you are using Microsoft 365, use XLOOKUP — it’s not only faster, it also lets you search in any direction (up, down, left, right).

There are two ways to use LOOKUP: Vector form and Array form

  • Vector form: Use this form of LOOKUP to search one row or one column for a value. Use the vector form when you want to specify the range that contains the values that you want to match. For example, if you want to search for a value in column A, down to row 6.

    Example of a vector

  • Array form: We strongly recommend using VLOOKUP or HLOOKUP instead of the array form. Watch this video about using VLOOKUP. The array form is provided for compatibility with other spreadsheet programs, but it’s functionality is limited.

    An array is a collection of values in rows and columns (like a table) that you want to search. For example, if you want to search columns A and B, down to row 6. LOOKUP will return the nearest match. To use the array form, your data must be sorted.

    Example of a table, which is an array

Vector form

The vector form of LOOKUP looks in a one-row or one-column range (known as a vector) for a value and returns a value from the same position in a second one-row or one-column range.

Syntax

LOOKUP(lookup_value, lookup_vector, [result_vector])

The LOOKUP function vector form syntax has the following arguments:

  • lookup_value    Required. A value that LOOKUP searches for in the first vector. Lookup_value can be a number, text, a logical value, or a name or reference that refers to a value.

  • lookup_vector    Required. A range that contains only one row or one column. The values in lookup_vector can be text, numbers, or logical values.

    Important: The values in lookup_vector must be placed in ascending order: …, -2, -1, 0, 1, 2, …, A-Z, FALSE, TRUE; otherwise, LOOKUP might not return the correct value. Uppercase and lowercase text are equivalent.

  • result_vector    Optional. A range that contains only one row or column. The result_vector argument must be the same size as lookup_vector. It has to be the same size.

Remarks

  • If the LOOKUP function can’t find the lookup_value, the function matches the largest value in lookup_vector that is less than or equal to lookup_value.

  • If lookup_value is smaller than the smallest value in lookup_vector, LOOKUP returns the #N/A error value.

Vector examples

You can try out these examples in your own Excel worksheet to learn how the LOOKUP function works. In the first example, you’re going to end up with a spreadsheet that looks similar to this one:

An example of using the LOOKUP function

  1. Copy the data in following table, and paste it into a new Excel worksheet.

    Copy this data into column A

    Copy this data into column B

    Frequency

    4.14

    Color

    red

    4.19

    orange

    5.17

    yellow

    5.77

    green

    6.39

    blue

  2. Next, copy the LOOKUP formulas from the following table into column D of your worksheet.

    Copy this formula into the D column

    Here’s what this formula does

    Here’s the result you’ll see

    Formula

    =LOOKUP(4.19, A2:A6, B2:B6)

    Looks up 4.19 in column A, and returns the value from column B that is in the same row.

    orange

    =LOOKUP(5.75, A2:A6, B2:B6)

    Looks up 5.75 in column A, matches the nearest smaller value (5.17), and returns the value from column B that is in the same row.

    yellow

    =LOOKUP(7.66, A2:A6, B2:B6)

    Looks up 7.66 in column A, matches the nearest smaller value (6.39), and returns the value from column B that is in the same row.

    blue

    =LOOKUP(0, A2:A6, B2:B6)

    Looks up 0 in column A, and returns an error because 0 is less than the smallest value (4.14) in column A.

    #N/A

  3. For these formulas to show results, you may need to select them in your Excel worksheet, press F2, and then press Enter. If you need to, adjust the column widths to see all the data.

Array form

The array form of LOOKUP looks in the first row or column of an array for the specified value and returns a value from the same position in the last row or column of the array. Use this form of LOOKUP when the values that you want to match are in the first row or column of the array.

Syntax

LOOKUP(lookup_value, array)

The LOOKUP function array form syntax has these arguments:

  • lookup_value    Required. A value that LOOKUP searches for in an array. The lookup_value argument can be a number, text, a logical value, or a name or reference that refers to a value.

    • If LOOKUP can’t find the value of lookup_value, it uses the largest value in the array that is less than or equal to lookup_value.

    • If the value of lookup_value is smaller than the smallest value in the first row or column (depending on the array dimensions), LOOKUP returns the #N/A error value.

  • array    Required. A range of cells that contains text, numbers, or logical values that you want to compare with lookup_value.

    The array form of LOOKUP is very similar to the HLOOKUP and VLOOKUP functions. The difference is that HLOOKUP searches for the value of lookup_value in the first row, VLOOKUP searches in the first column, and LOOKUP searches according to the dimensions of array.

    • If array covers an area that is wider than it is tall (more columns than rows), LOOKUP searches for the value of lookup_value in the first row.

    • If an array is square or is taller than it is wide (more rows than columns), LOOKUP searches in the first column.

    • With the HLOOKUP and VLOOKUP functions, you can index down or across, but LOOKUP always selects the last value in the row or column.

      Important: The values in array must be placed in ascending order: …, -2, -1, 0, 1, 2, …, A-Z, FALSE, TRUE; otherwise, LOOKUP might not return the correct value. Uppercase and lowercase text are equivalent.

Содержание

  1. Finding of the value in the column and the row of the Excel table
  2. Finding values in the Excel table
  3. Search of the value in the Excel ROW
  4. The principle of the formula for finding the value in the Excel ROW:
  5. How can I get to the column headings from a single cell value?
  6. Search the value in the Excel column
  7. The principle of the formula for finding the value in the Excel column
  8. LOOKUP function
  9. There are two ways to use LOOKUP: Vector form and Array form
  10. Vector form
  11. Syntax
  12. Remarks
  13. Vector examples
  14. Array form
  15. Syntax

Finding of the value in the column and the row of the Excel table

We have the table in which the sales volumes of certain products are recorded in different months. It is necessary to find the data in the table, and the search criteria will be the headings of rows and columns. But the search must be performed separately by the range of the row or column. That is, only one of the criteria will be used. Therefore, you can`t apply the INDEX function here, but you need a special formula.

Finding values in the Excel table

To solve this problem, let us illustrate the example in the schematic table that corresponds to the conditions are described above.

The sheet with the table to search for values vertically and horizontally:

Above this table we can see the row with results. In the cell B1 we introduce the criterion for the search query, that is, the column header or the ROW name. And in the cell D1, to a search formula should return to the result of the calculation of the corresponding value. Then the second formula will work in the cell F1. She will already use the values of the cells B1 and D1 as the criteria for searching of the corresponding month.

Search of the value in the Excel ROW

Now we are learning, in what maximum volume and in what month has been the maximum sale of the Product 4.

To search by columns:

  1. In the cell B1 you need to enter the value of the Product 4 — the name of the row, that will act as the criterion.
  2. In the cell D1 you need to enter the following:
  3. To confirm after entering the formula, you need to press the CTRL + SHIFT + Enter hotkey combination, because she must be executed in the array. If everything is done correctly, the curly braces will appear in the formula ROW.
  4. In the cell F1 you need to enter the second:
  5. For confirmation, to press the key combination CTRL + SHIFT + Enter again.

So we have found, in what month and what was the largest sale of the Product 4 for two quarters.

The principle of the formula for finding the value in the Excel ROW:

In the first argument of the VLOOKUP function (Vertical Look Up), indicates to the reference to the cell, where the search criterion is located. In the second argument indicates to the range of the cells for viewing during in the process of searching.

In the third argument of the VLOOKUP function should be indicated the number of the column from which you should to take the value against of the row named the Item 4. But since we do not previously know this number, we use the COLUMN function for creating the array of column numbers for the range B4:G15.

This allows the VLOOKUP function to collect the whole array of values. As a result, all relevant values are stored in memory for each column in the row Product 4 (namely: 360; 958; 201; 605; 462; 832). After that, the MAX function will only take the maximum number from this array and return it as the value for the cell D1, as the result of calculating.

As you can see, the construction of the formula is simple and concise. On its basis, it is possible in a similar way to find other indicators for a certain product. For example, the minimum or an average value of sales volume you need to find using for this purpose MIN or AVERAGE functions. Nothing hinders you from applying this skeleton of the formula to apply with more complex functions for implementation the most comfortable analysis of the sales report.

How can I get to the column headings from a single cell value?

For example, how effectively we displayed the month with the maximum sale, using of the second. It’s not difficult to notice that in the second formula we used the skeleton of the first formula without the MAX function. The main structure of the function is: VLOOKUP. We replaced the MAX on the MATCH, which in the first argument uses the value obtained by the previous formula. It acts as the criterion for searching for the month now.

And as a result, the MATCH function returns the column number 2, where the maximum value of the sales volume for the product is located for the product 4. After that, the INDEX function is included in the work. This function returns the value by the number of terms and column from the range specified in its arguments. Because the we have the number of column 2, and the row number in the range where the names of months are stored in any cases will be the value 1. Then we have the INDEX function to get the corresponding value from the range of B4:G4 — February (the second month).

Search the value in the Excel column

The second version of the task will be searching in the table with using the month name as the criterion. In such cases, we have to change the skeleton of our formula: the VLOOKUP function is replaced by the HLOOKUP (Horizontal Look Up) one, and the COLUMN function is replaced by the row one.

This will allow us to know what volume and what of the product the maximum sale was in a certain month.

To find what kind of the product had the maximum sales in a certain month, you should:

  1. In the cell B2 to enter the name of the month June — this value will be used as the search criterion.
  2. In the cell D2, you should to enter the formula:
  3. To confirm after entering the formula you need to press the combination of keys CTRL + SHIFT + Enter, as this formula will be executed in the array. And the curly braces will appear in the function ROW.
  4. In the cell F1, you need to enter the second:
  5. You need to click CTRL + SHIFT + Enter for confirmation again.

The principle of the formula for finding the value in the Excel column

In the first argument of the HLOOKUP function, we indicate to the reference by the cell with the criterion for the search. In the second argument specifies the reference to the table argument being scanned. The third argument is generated by the ROW function, what creates in the array of ROW numbers of 10 elements in memory. So there are 10 rows in the table section.

Further the HLOOKUP function, alternately using to each number of the row, creates the array of corresponding sales values from the table for the certain month (June). Further, the MAX function is left only to select the maximum value from this array.

Then just a little modifying to the first formula by using the INDEX and MATCH functions, we created the second function to display the names of the table rows according to the cell value. The names of the corresponding rows (products) we output in F2.

ATTENTION! When using the formula skeleton for other tasks, you need always to pay attention to the second and the third argument of the search HLOOKUP function. The number of covered rows in the range is specified in the argument, must match with the number of rows in the table. And also the numbering should begin with the second ROW!

Indeed, the content of the range generally we don’t care — we just need the row counter. That is, you need to change the arguments to: ROW(B2:B11) or ROW(C2:C11) — this does not affect in the quality of the formula. The main thing is that — there are 10 rows in these ranges, as well as in the table. And the numbering starts from the second row!

Источник

LOOKUP function

Use LOOKUP, one of the lookup and reference functions, when you need to look in a single row or column and find a value from the same position in a second row or column.

For example, let’s say you know the part number for an auto part, but you don’t know the price. You can use the LOOKUP function to return the price in cell H2 when you enter the auto part number in cell H1.

Use the LOOKUP function to search one row or one column. In the above example, we’re searching prices in column D.

Tips: Consider one of the newer lookup functions, depending on which version you are using.

Use VLOOKUP to search one row or column, or to search multiple rows and columns (like a table). It’s a much improved version of LOOKUP. Watch this video about how to use VLOOKUP.

If you are using Microsoft 365, use XLOOKUP — it’s not only faster, it also lets you search in any direction (up, down, left, right).

There are two ways to use LOOKUP: Vector form and Array form

Vector form: Use this form of LOOKUP to search one row or one column for a value. Use the vector form when you want to specify the range that contains the values that you want to match. For example, if you want to search for a value in column A, down to row 6.

Array form: We strongly recommend using VLOOKUP or HLOOKUP instead of the array form. Watch this video about using VLOOKUP. The array form is provided for compatibility with other spreadsheet programs, but it’s functionality is limited.

An array is a collection of values in rows and columns (like a table) that you want to search. For example, if you want to search columns A and B, down to row 6. LOOKUP will return the nearest match. To use the array form, your data must be sorted.

Vector form

The vector form of LOOKUP looks in a one-row or one-column range (known as a vector) for a value and returns a value from the same position in a second one-row or one-column range.

Syntax

LOOKUP(lookup_value, lookup_vector, [result_vector])

The LOOKUP function vector form syntax has the following arguments:

lookup_value Required. A value that LOOKUP searches for in the first vector. Lookup_value can be a number, text, a logical value, or a name or reference that refers to a value.

lookup_vector Required. A range that contains only one row or one column. The values in lookup_vector can be text, numbers, or logical values.

Important: The values in lookup_vector must be placed in ascending order: . -2, -1, 0, 1, 2, . A-Z, FALSE, TRUE; otherwise, LOOKUP might not return the correct value. Uppercase and lowercase text are equivalent.

result_vector Optional. A range that contains only one row or column. The result_vector argument must be the same size as lookup_vector. It has to be the same size.

If the LOOKUP function can’t find the lookup_value, the function matches the largest value in lookup_vector that is less than or equal to lookup_value.

If lookup_value is smaller than the smallest value in lookup_vector, LOOKUP returns the #N/A error value.

Vector examples

You can try out these examples in your own Excel worksheet to learn how the LOOKUP function works. In the first example, you’re going to end up with a spreadsheet that looks similar to this one:

Copy the data in following table, and paste it into a new Excel worksheet.

Copy this data into column A

Copy this data into column B

Next, copy the LOOKUP formulas from the following table into column D of your worksheet.

Copy this formula into the D column

Here’s what this formula does

Here’s the result you’ll see

=LOOKUP(4.19, A2:A6, B2:B6)

Looks up 4.19 in column A, and returns the value from column B that is in the same row.

=LOOKUP(5.75, A2:A6, B2:B6)

Looks up 5.75 in column A, matches the nearest smaller value (5.17), and returns the value from column B that is in the same row.

=LOOKUP(7.66, A2:A6, B2:B6)

Looks up 7.66 in column A, matches the nearest smaller value (6.39), and returns the value from column B that is in the same row.

=LOOKUP(0, A2:A6, B2:B6)

Looks up 0 in column A, and returns an error because 0 is less than the smallest value (4.14) in column A.

For these formulas to show results, you may need to select them in your Excel worksheet, press F2, and then press Enter. If you need to, adjust the column widths to see all the data.

Array form

Tip: We strongly recommend using VLOOKUP or HLOOKUP instead of the array form. See this video about VLOOKUP; it provides examples. The array form of LOOKUP is provided for compatibility with other spreadsheet programs, but its functionality is limited.

The array form of LOOKUP looks in the first row or column of an array for the specified value and returns a value from the same position in the last row or column of the array. Use this form of LOOKUP when the values that you want to match are in the first row or column of the array.

Syntax

The LOOKUP function array form syntax has these arguments:

lookup_value Required. A value that LOOKUP searches for in an array. The lookup_value argument can be a number, text, a logical value, or a name or reference that refers to a value.

If LOOKUP can’t find the value of lookup_value, it uses the largest value in the array that is less than or equal to lookup_value.

If the value of lookup_value is smaller than the smallest value in the first row or column (depending on the array dimensions), LOOKUP returns the #N/A error value.

array Required. A range of cells that contains text, numbers, or logical values that you want to compare with lookup_value.

The array form of LOOKUP is very similar to the HLOOKUP and VLOOKUP functions. The difference is that HLOOKUP searches for the value of lookup_value in the first row, VLOOKUP searches in the first column, and LOOKUP searches according to the dimensions of array.

If array covers an area that is wider than it is tall (more columns than rows), LOOKUP searches for the value of lookup_value in the first row.

If an array is square or is taller than it is wide (more rows than columns), LOOKUP searches in the first column.

With the HLOOKUP and VLOOKUP functions, you can index down or across, but LOOKUP always selects the last value in the row or column.

Important: The values in array must be placed in ascending order: . -2, -1, 0, 1, 2, . A-Z, FALSE, TRUE; otherwise, LOOKUP might not return the correct value. Uppercase and lowercase text are equivalent.

Источник

Метод Find объекта Range для поиска ячейки по ее данным в VBA Excel. Синтаксис и компоненты. Знаки подстановки для поисковой фразы. Простые примеры.

Метод Find объекта Range предназначен для поиска ячейки и сведений о ней в заданном диапазоне по ее значению, формуле и примечанию. Чаще всего этот метод используется для поиска в таблице ячейки по слову, части слова или фразе, входящей в ее значение.

Синтаксис метода Range.Find

Expression.Find(What, After, LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, MatchByte, SearchFormat)

Expression – это переменная или выражение, возвращающее объект Range, в котором будет осуществляться поиск.

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

Метод Range.Find возвращает объект Range, представляющий из себя первую ячейку, в которой найдена поисковая фраза (параметр What). Если совпадение не найдено, возвращается значение Nothing.

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

Параметры метода Range.Find

Наименование Описание
Обязательный параметр
What Данные для поиска, которые могут быть представлены строкой или другим типом данных Excel. Тип данных параметра — Variant.
Необязательные параметры
After Ячейка, после которой следует начать поиск.
LookIn Уточняет область поиска. Список констант xlFindLookIn:

  • xlValues (-4163) – значения;
  • xlComments (-4144) – примечания*;
  • xlNotes (-4144) – примечания*;
  • xlFormulas (-4123) – формулы.
LookAt Поиск частичного или полного совпадения. Список констант xlLookAt:

  • xlWhole (1) – полное совпадение;
  • xlPart (2) – частичное совпадение.
SearchOrder Определяет способ поиска. Список констант xlSearchOrder:

  • xlByRows (1) – поиск по строкам;
  • xlByColumns (2) – поиск по столбцам.
SearchDirection Определяет направление поиска. Список констант xlSearchDirection:

  • xlNext (1) – поиск вперед;
  • xlPrevious (2) – поиск назад.
MatchCase Определяет учет регистра:

  • False (0) – поиск без учета регистра (по умолчанию);
  • True (1) – поиск с учетом регистра.
MatchByte Условия поиска при использовании двухбайтовых кодировок:

  • False (0) – двухбайтовый символ может соответствовать однобайтовому символу;
  • True (1) – двухбайтовый символ должен соответствовать только двухбайтовому символу.
SearchFormat Формат поиска – используется вместе со свойством Application.FindFormat.

* Примечания имеют две константы с одним значением. Проверяется очень просто: MsgBox xlComments и MsgBox xlNotes.

В справке Microsoft тип данных всех параметров, кроме SearchDirection, указан как Variant.

Знаки подстановки для поисковой фразы

Условные знаки в шаблоне поисковой фразы:

  • ? – знак вопроса обозначает любой отдельный символ;
  • * – звездочка обозначает любое количество любых символов, в том числе ноль символов;
  • ~ – тильда ставится перед ?, * и ~, чтобы они обозначали сами себя (например, чтобы тильда в шаблоне обозначала сама себя, записать ее нужно дважды: ~~).

Простые примеры

При использовании метода Range.Find в VBA Excel необходимо учитывать следующие нюансы:

  1. Так как этот метод возвращает объект Range (в виде одной ячейки), присвоить его можно только объектной переменной, объявленной как Variant, Object или Range, при помощи оператора Set.
  2. Если поисковая фраза в заданном диапазоне найдена не будет, метод Range.Find возвратит значение Nothing. Обращение к свойствам несуществующей ячейки будет генерировать ошибки. Поэтому, перед использованием результатов поиска, необходимо проверить объектную переменную на содержание в ней значения Nothing.

В примерах используются переменные:

  • myPhrase – переменная для записи поисковой фразы;
  • myCell – переменная, которой присваивается первая найденная ячейка, содержащая поисковую фразу, или значение Nothing, если поисковая фраза не найдена.

Пример 1

Sub primer1()

Dim myPhrase As Variant, myCell As Range

myPhrase = «стакан»

Set myCell = Range(«A1:L30»).Find(myPhrase)

If Not myCell Is Nothing Then

MsgBox «Значение найденной ячейки: « & myCell

MsgBox «Строка найденной ячейки: « & myCell.Row

MsgBox «Столбец найденной ячейки: « & myCell.Column

MsgBox «Адрес найденной ячейки: « & myCell.Address

Else

MsgBox «Искомая фраза не найдена»

End If

End Sub

В этом примере мы присваиваем переменной myPhrase значение для поиска – "стакан". Затем проводим поиск этой фразы в диапазоне "A1:L30" с присвоением результата поиска переменной myCell. Далее проверяем переменную myCell, не содержит ли она значение Nothing, и выводим соответствующие сообщения.

Ознакомьтесь с работой кода VBA в случаях, когда в диапазоне "A1:L30" есть ячейка со строкой, содержащей подстроку "стакан", и когда такой ячейки нет.

Пример 2

Теперь посмотрим, как метод Range.Find отреагирует на поиск числа. В качестве диапазона поиска будем использовать первую строку активного листа Excel.

Sub primer2()

Dim myPhrase As Variant, myCell As Range

myPhrase = 526.15

Set myCell = Rows(1).Find(myPhrase)

If Not myCell Is Nothing Then

MsgBox «Значение найденной ячейки: « & myCell

Else: MsgBox «Искомая фраза не найдена»

End If

End Sub

Несмотря на то, что мы присвоили переменной числовое значение, метод Range.Find найдет ячейку со значением и 526,15, и 129526,15, и 526,15254. То есть, как и в предыдущем примере, поиск идет по подстроке.

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

Set myCell = Rows(1).Find(myPhrase, , , xlWhole)

Аналогично используются и другие необязательные параметры. Количество «лишних» запятых перед необязательным параметром должно соответствовать количеству пропущенных компонентов, предусмотренных синтаксисом метода Range.Find, кроме случаев указания необязательного параметра по имени, например: LookIn:=xlValues. Тогда используется одна запятая, независимо от того, сколько компонентов пропущено.

Пример 3

Допустим, у нас есть многострочная база данных в Excel. В первой колонке находятся даты. Нам необходимо создать отчет за какой-то период. Найти номер начальной строки для обработки можно с помощью следующего кода:

Sub primer3()

Dim myPhrase As Variant, myCell As Range

myPhrase = «01.02.2019»

myPhrase = CDate(myPhrase)

Set myCell = Range(«A:A»).Find(myPhrase)

If Not myCell Is Nothing Then

MsgBox «Номер начальной строки: « & myCell.Row

Else: MsgBox «Даты « & myPhrase & » в таблице нет»

End If

End Sub

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

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

Поиск перебором значений

Довольно простой в реализации способ. Например, найти в колонке «A» ячейку, содержащую «123» можно примерно так:

Sheets("Данные").Select
For y = 1 To Cells.SpecialCells(xlLastCell).Row
    If Cells(y, 1) = "123" Then
        Exit For
    End If
Next y
MsgBox "Нашел в строке: " + CStr(y)

Минусами этого так сказать «классического» способа являются: медленная работа и громоздкость. А плюсом является его гибкость, т.к. таким способом можно реализовать сколь угодно сложные варианты поиска с различными вычислениями и т.п.

Поиск функцией Find

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

Sheets("Данные").Select
Set fcell = Columns("A:A").Find("123")
If Not fcell Is Nothing Then
    MsgBox "Нашел в строке: " + CStr(fcell.Row)
End If

Вкратце опишу что делают строчки данного кода:
1-я строка: Выбираем в книге лист «Данные»;
2-я строка: Осуществляем поиск значения «123» в колонке «A», результат поиска будет в fcell;
3-я строка: Если удалось найти значение, то fcell будет содержать Range-объект, в противном случае — будет пустой, т.е. Nothing.

Полностью синтаксис оператора поиска выглядит так:

Find(What, After, LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, MatchByte, SearchFormat)

What — Строка с текстом, который ищем или любой другой тип данных Excel

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

LookIn — Тип искомых данных. Может принимать одно из значений: xlFormulas (формулы), xlValues (значения), или xlNotes (примечания).

LookAt — Одно из значений: xlWhole (полное совпадение) или xlPart (частичное совпадение).

SearchOrder — Одно из значений: xlByRows (просматривать по строкам) или xlByColumns (просматривать по столбцам)

SearchDirection — Одно из значений: xlNext (поиск вперед) или xlPrevious (поиск назад)

MatchCase — Одно из значений: True (поиск чувствительный к регистру) или False (поиск без учета регистра)

MatchByte — Применяется при использовании мультибайтных кодировок: True (найденный мультибайтный символ должен соответствовать только мультибайтному символу) или False (найденный мультибайтный символ может соответствовать однобайтному символу)

SearchFormat — Используется вместе с FindFormat. Сначала задается значение FindFormat (например, для поиска ячеек с курсивным шрифтом так: Application.FindFormat.Font.Italic = True), а потом при использовании метода Find указываем параметр SearchFormat = True. Если при поиске не нужно учитывать формат ячеек, то нужно указать SearchFormat = False.

Чтобы продолжить поиск, можно использовать FindNext (искать «далее») или FindPrevious (искать «назад»).

Примеры поиска функцией Find

Пример 1: Найти в диапазоне «A1:A50» все ячейки с текстом «asd» и поменять их все на «qwe»

With Worksheets(1).Range("A1:A50")
  Set c = .Find("asd", LookIn:=xlValues)
  Do While Not c Is Nothing
    c.Value = "qwe"
    Set c = .FindNext(c)
  Loop
End With

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

Пример 2: Правильный поиск значения с использованием FindNext, не приводящий к зацикливанию.

With Worksheets(1).Range("A1:A50")
  Set c = .Find("asd", lookin:=xlValues)
  If Not c Is Nothing Then
    firstResult = c.Address
    Do
      c.Font.Bold = True
      Set c = .FindNext(c)
      If c Is Nothing Then Exit Do
    Loop While c.Address <> firstResult
  End If
End With

В ниже следующем примере используется другой вариант продолжения поиска — с помощью той же функции Find с параметром After. Когда найдена очередная ячейка, следующий поиск будет осуществляться уже после нее. Однако, как и с FindNext, когда будет достигнут конец диапазона, Find продолжит поиск с его начала, поэтому, чтобы не произошло зацикливания, необходимо проверять совпадение с первым результатом поиска.

Пример 3: Продолжение поиска с использованием Find с параметром After.

With Worksheets(1).Range("A1:A50")
  Set c = .Find("asd", lookin:=xlValues)
  If Not c Is Nothing Then
    firstResult = c.Address
    Do
      c.Font.Bold = True
      Set c = .Find("asd", After:=c, lookin:=xlValues)
      If c Is Nothing Then Exit Do
    Loop While c.Address <> firstResult
  End If
End With

Следующий пример демонстрирует применение SearchFormat для поиска по формату ячейки. Для указания формата необходимо задать свойство FindFormat.

Пример 4: Найти все ячейки с шрифтом «курсив» и поменять их формат на обычный (не «курсив»)

lLastRow = Cells.SpecialCells(xlLastCell).Row
lLastCol = Cells.SpecialCells(xlLastCell).Column
Application.FindFormat.Font.Italic = True
With Worksheets(1).Range(Cells(1, 1), Cells(lLastRow, lLastCol))
  Set c = .Find("", SearchFormat:=True)
  Do While Not c Is Nothing
    c.Font.Italic = False
    Set c = .Find("", After:=c, SearchFormat:=True)
  Loop
End With

Примечание: В данном примере намеренно не используется FindNext для поиска следующей ячейки, т.к. он не учитывает формат (статья об этом: https://support.microsoft.com/ru-ru/kb/282151)

Коротко опишу алгоритм поиска Примера 4. Первые две строки определяют последнюю строку (lLastRow) на листе и последний столбец (lLastCol). 3-я строка задает формат поиска, в данном случае, будем искать ячейки с шрифтом Italic. 4-я строка определяет область ячеек с которой будет работать программа (с ячейки A1 и до последней строки и последнего столбца). 5-я строка осуществляет поиск с использованием SearchFormat. 6-я строка — цикл пока результат поиска не будет пустым. 7-я строка — меняем шрифт на обычный (не курсив), 8-я строка продолжаем поиск после найденной ячейки.

Хочу обратить внимание на то, что в этом примере я не стал использовать «защиту от зацикливания», как в Примерах 2 и 3, т.к. шрифт меняется и после «прохождения» по всем ячейкам, больше не останется ни одной ячейки с курсивом.

Свойство FindFormat можно задавать разными способами, например, так:

With Application.FindFormat.Font 
  .Name = "Arial" 
  .FontStyle = "Regular" 
  .Size = 10 
End With

Поиск последней заполненной ячейки с помощью Find

Следующий пример — применение функции Find для поиска последней ячейки с заполненными данными. Использованные в Примере 4 SpecialCells находит последнюю ячейку даже если она не содержит ничего, но отформатирована или в ней раньше были данные, но были удалены.

Пример 5: Найти последнюю колонку и столбец, заполненные данными

Set c = Worksheets(1).UsedRange.Find("*", SearchDirection:=xlPrevious)
If Not c Is Nothing Then
  lLastRow = c.Row: lLastCol = c.Column 
Else
  lLastRow = 1: lLastCol = 1
End If
MsgBox "lLastRow=" & lLastRow & " lLastCol=" & lLastCol

В этом примере используется UsedRange, который так же как и SpecialCells возвращает все используемые ячейки, в т.ч. и те, что были использованы ранее, а сейчас пустые. Функция Find ищет ячейку с любым значением с конца диапазона.

Поиск по шаблону (маске)

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

Пример 6: Выделить красным шрифтом ячейки, в которых текст начинается со слова из 4-х букв, первая и последняя буквы «т», при этом после этого слова может следовать любой текст.

With Worksheets(1).Cells
  Set c = .Find("т??т*", LookIn:=xlValues, LookAt:=xlWhole)
  If Not c Is Nothing Then
    firstResult = c.Address
    Do
      c.Font.Color = RGB(255, 0, 0)
      Set c = .FindNext(c)
      If c Is Nothing Then Exit Do
    Loop While c.Address <> firstResult
  End If
End With

Для поиска функцией Find по маске (шаблону) можно применять символы:
* — для обозначения любого количества любых символов;
? — для обозначения одного любого символа;
~ — для обозначения символов *, ? и ~. (т.е. чтобы искать в тексте вопросительный знак, нужно написать ~?, чтобы искать именно звездочку (*), нужно написать ~* и наконец, чтобы найти в тексте тильду, необходимо написать ~~)

Поиск в скрытых строках и столбцах

Для поиска в скрытых ячейках нужно учитывать лишь один нюанс: поиск нужно осуществлять в формулах, а не в значениях, т.е. нужно использовать LookIn:=xlFormulas

Поиск даты с помощью Find

Если необходимо найти текущую дату или какую-то другую дату на листе Excel или в диапазоне с помощью Find, необходимо учитывать несколько нюансов:

  • Тип данных Date в VBA представляется в виде #[месяц]/[день]/[год]#, соответственно, если необходимо найти фиксированную дату, например, 01 марта 2018 года, необходимо искать #3/1/2018#, а не «01.03.2018»
  • В зависимости от формата ячеек, дата может выглядеть по-разному, поэтому, чтобы искать дату независимо от формата, поиск нужно делать не в значениях, а в формулах, т.е. использовать LookIn:=xlFormulas

Приведу несколько примеров поиска даты.

Пример 7: Найти текущую дату на листе независимо от формата отображения даты.

d = Date
Set c = Cells.Find(d, LookIn:=xlFormulas, LookAt:=xlWhole)
If Not c Is Nothing Then
  MsgBox "Нашел"
Else
  MsgBox "Не нашел"
End If

Пример 8: Найти 1 марта 2018 г.

d = #3/1/2018#
Set c = Cells.Find(d, LookIn:=xlFormulas, LookAt:=xlWhole)
If Not c Is Nothing Then
  MsgBox "Нашел"
Else
  MsgBox "Не нашел"
End If

Искать часть даты — сложнее. Например, чтобы найти все ячейки, где месяц «март», недостаточно искать «03» или «3». Не работает с датами так же и поиск по шаблону. Единственный вариант, который я нашел — это выбрать формат в котором месяц прописью для ячеек с датами и искать слово «март» в xlValues.

Тем не менее, можно найти, например, 1 марта независимо от года.

Пример 9: Найти 1 марта любого года.

d = #3/1/1900#
Set c = Cells.Find(Format(d, "m/d/"), LookIn:=xlFormulas, LookAt:=xlPart)
If Not c Is Nothing Then
  MsgBox "Нашел"
Else
  MsgBox "Не нашел"
End If

We have the table in which the sales volumes of certain products are recorded in different months. It is necessary to find the data in the table, and the search criteria will be the headings of rows and columns. But the search must be performed separately by the range of the row or column. That is, only one of the criteria will be used. Therefore, you can`t apply the INDEX function here, but you need a special formula.



Finding values in the Excel table

To solve this problem, let us illustrate the example in the schematic table that corresponds to the conditions are described above.

The sheet with the table to search for values vertically and horizontally:

values vertically and horizontally.

Above this table we can see the row with results. In the cell B1 we introduce the criterion for the search query, that is, the column header or the ROW name. And in the cell D1, to a search formula should return to the result of the calculation of the corresponding value. Then the second formula will work in the cell F1. She will already use the values of the cells B1 and D1 as the criteria for searching of the corresponding month.



Search of the value in the Excel ROW

Now we are learning, in what maximum volume and in what month has been the maximum sale of the Product 4.

To search by columns:

  1. In the cell B1 you need to enter the value of the Product 4 — the name of the row, that will act as the criterion.
  2. In the cell D1 you need to enter the following:
  3. To confirm after entering the formula, you need to press the CTRL + SHIFT + Enter hotkey combination, because she must be executed in the array. If everything is done correctly, the curly braces will appear in the formula ROW.
  4. maximum volume.

  5. In the cell F1 you need to enter the second:
  6. For confirmation, to press the key combination CTRL + SHIFT + Enter again.

found.

So we have found, in what month and what was the largest sale of the Product 4 for two quarters.

The principle of the formula for finding the value in the Excel ROW:

In the first argument of the VLOOKUP function (Vertical Look Up), indicates to the reference to the cell, where the search criterion is located. In the second argument indicates to the range of the cells for viewing during in the process of searching.

In the third argument of the VLOOKUP function should be indicated the number of the column from which you should to take the value against of the row named the Item 4. But since we do not previously know this number, we use the COLUMN function for creating the array of column numbers for the range B4:G15.

This allows the VLOOKUP function to collect the whole array of values. As a result, all relevant values are stored in memory for each column in the row Product 4 (namely: 360; 958; 201; 605; 462; 832). After that, the MAX function will only take the maximum number from this array and return it as the value for the cell D1, as the result of calculating.

As you can see, the construction of the formula is simple and concise. On its basis, it is possible in a similar way to find other indicators for a certain product. For example, the minimum or an average value of sales volume you need to find using for this purpose MIN or AVERAGE functions. Nothing hinders you from applying this skeleton of the formula to apply with more complex functions for implementation the most comfortable analysis of the sales report.

How can I get to the column headings from a single cell value?

For example, how effectively we displayed the month with the maximum sale, using of the second. It’s not difficult to notice that in the second formula we used the skeleton of the first formula without the MAX function. The main structure of the function is: VLOOKUP. We replaced the MAX on the MATCH, which in the first argument uses the value obtained by the previous formula. It acts as the criterion for searching for the month now.

And as a result, the MATCH function returns the column number 2, where the maximum value of the sales volume for the product is located for the product 4. After that, the INDEX function is included in the work. This function returns the value by the number of terms and column from the range specified in its arguments. Because the we have the number of column 2, and the row number in the range where the names of months are stored in any cases will be the value 1. Then we have the INDEX function to get the corresponding value from the range of B4:G4 — February (the second month).

Search the value in the Excel column

The second version of the task will be searching in the table with using the month name as the criterion. In such cases, we have to change the skeleton of our formula: the VLOOKUP function is replaced by the HLOOKUP (Horizontal Look Up) one, and the COLUMN function is replaced by the row one.

This will allow us to know what volume and what of the product the maximum sale was in a certain month.

To find what kind of the product had the maximum sales in a certain month, you should:

  1. In the cell B2 to enter the name of the month June — this value will be used as the search criterion.
  2. In the cell D2, you should to enter the formula:
  3. To confirm after entering the formula you need to press the combination of keys CTRL + SHIFT + Enter, as this formula will be executed in the array. And the curly braces will appear in the function ROW.
  4. Formula.

  5. In the cell F1, you need to enter the second:
  6. You need to click CTRL + SHIFT + Enter for confirmation again.

Exaple.

The principle of the formula for finding the value in the Excel column

In the first argument of the HLOOKUP function, we indicate to the reference by the cell with the criterion for the search. In the second argument specifies the reference to the table argument being scanned. The third argument is generated by the ROW function, what creates in the array of ROW numbers of 10 elements in memory. So there are 10 rows in the table section.

Further the HLOOKUP function, alternately using to each number of the row, creates the array of corresponding sales values from the table for the certain month (June). Further, the MAX function is left only to select the maximum value from this array.

Then just a little modifying to the first formula by using the INDEX and MATCH functions, we created the second function to display the names of the table rows according to the cell value. The names of the corresponding rows (products) we output in F2.

ATTENTION! When using the formula skeleton for other tasks, you need always to pay attention to the second and the third argument of the search HLOOKUP function. The number of covered rows in the range is specified in the argument, must match with the number of rows in the table. And also the numbering should begin with the second ROW!

Download example search values in the columns and rows

Read also: The searching of the value in a range Excel table in columns and rows

Indeed, the content of the range generally we don’t care — we just need the row counter. That is, you need to change the arguments to: ROW(B2:B11) or ROW(C2:C11) — this does not affect in the quality of the formula. The main thing is that — there are 10 rows in these ranges, as well as in the table. And the numbering starts from the second row!

Понравилась статья? Поделить с друзьями:
  • Excel find what column a value is in
  • Excel find values not in column
  • Excel find value from cell
  • Excel find the value of a cell
  • Excel find text not found