Worksheetfunction find vba excel

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

WorksheetFunction.Find method (Excel)

vbaxl10.chm137129

vbaxl10.chm137129

excel

Excel.WorksheetFunction.Find

4e87760e-ffc9-39a0-a072-a077ce1ef54b

05/22/2019

medium

WorksheetFunction.Find method (Excel)

Finds specific information on a worksheet.

Syntax

expression.Find (Arg1, Arg2, Arg3)

expression A variable that represents a WorksheetFunction object.

Parameters

Name Required/Optional Data type Description
Arg1 Required String The name of the worksheet.
Arg2 Required String The name of the range.
Arg3 Optional Variant The name of an argument to refine the search.

Return value

Double

[!includeSupport and feedback]

Sub Excel_FIND_Function()

Dim ws As Worksheet

Set ws = Worksheets(«FIND»)

ws.Range(«E5») = Application.WorksheetFunction.Find(ws.Range(«C5»), ws.Range(«B5»))
ws.Range(«E6») = Application.WorksheetFunction.Find(ws.Range(«C6»), ws.Range(«B6»), ws.Range(«D6»))
ws.Range(«E7») = Application.WorksheetFunction.Find(ws.Range(«C7»), ws.Range(«B7»), ws.Range(«D7»))

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Worksheet Name: Have a worksheet named FIND.
String Range: Have the range of strings that you want to search within captured in range («B4:B7»).
Find sub-string: Have the sub-string that you want to search for in range («C5:C7»).
Start Position: In this example the start position only applies to the bottom two examples. Therefore, if using the exact same VBA code ensure that the start position value is captured in range («D6:D7»).

ADJUSTABLE PARAMETERS
Output Range: Select the output range by changing the cell references («E5»), («E6») and («E7») in the VBA code to any cell in the worksheet, that doesn’t conflict with formula.
String Range: Select the range of strings that you want to search within by changing the range («B5:B7») in the VBA code to any cell in the worksheet, that doesn’t conflict with formula.
Find sub-string: Select the sub-string that you want to search for by changing the cell references («C5»), («C6») and («C7») to any range in the worksheet, that doesn’t conflict with the formula.
Start Position: Select the start position value by changing the range («D6:D7») to any range in the worksheet, that doesn’t conflict with the formula.

Поиск какого-либо значения в ячейках 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

This tutorial demonstrates how to use the FIND Function in Excel and Google Sheets to find text within text.

FIND Main Function

What Is the FIND Function?

The Excel FIND Function tries to find string of text within another text string. If it finds it, FIND returns the numerical position of that string.

Note: FIND is case-sensitive. So, “text” will NOT match “TEXT”. For case-insensitive searches, use the SEARCH Function.

How to Use the FIND Function

To use the Excel FIND Function, type the following:

=FIND("e", "elephant")

elephant

In this case, Excel will return the number 1, because “e” is the first character in the string “elephant”.

Let’s take a look at some more examples:

Start Number (start_num)

The start number tells FIND what numerical position in the string to start looking from. If you don’t define it, FIND will start from the beginning of the string.

=FIND(B3,C3)

No Start Num

Now let’s try defining a start number of 2. Here, we see that FIND returns 3. Because it starts looking from the second character, it misses the first “e” and finds the second:

=FIND(B3,C3,D3)

Start Num

Start Number (start_num) Errors

If you want to use a start number, it must:

  • be a whole number
  • be a positive number
  • be smaller than the length of the string you are looking in
  • not refer to a blank cell, if you define it as a cell reference

Otherwise, FIND will return a #VALUE! error as shown below:

Start Num Errors

Unsuccessful Searches Return a #VALUE! Error

If FIND does not locate the string you’re looking for, it will return a value error:

Unsuccessful Search

FIND is Case-Sensitive

In the example below, we’re searching for “abc”. FIND returns 10 because it is case-sensitive – it ignores “ABC” and the other variations:

Case Sensitive

FIND Does Not Accept Wildcards

You cannot use wildcards with FIND. Below, we’re looking for “?000”. In a wildcard search, this would mean “any character followed by three zeroes”. But FIND takes this literally to mean “a question mark followed by three zeroes”:

Wildcard 1

The same applies to the asterisk wildcard:

Wildcard 2

Instead, to search text with wildcards, you can use the SEARCH Function:

Wildcard 1

Wildcard 02

How to Split First and Last Names from a Cell with FIND

If your spreadsheet has a list of names with both the first and last names in the same cell, you might want to split them out to make sorting easier. FIND can do that for you – with a little help from some other functions.

Getting the First Name

The LEFT Function returns a given number of characters from a string, starting from the left.

We can use it to get the first name, but since names are different lengths, how do we know how many characters to return?

Easy – we just use FIND to return the position of the space between the first and last name, subtract 1 from that, and that’s how many characters we tell LEFT to give us.

The formula looks like this:

=LEFT(B3,FIND(“ “,B3)-1)

First Name

Getting the Last Name

The RIGHT Function returns a given number of characters from a string, starting from the right.

We have the same problem here as with the first name, but the solution is different, because we have to get the number of characters between the space and the right edge of the string, not the left.

To get that, we use FIND to tell us where the space is, and then subtract that number from the total number of characters in the string, which the LEN Function can give us.

The formula looks like this:

=RIGHT(B3,LEN(B3)-FIND(" ",B3))

Last Name

If the name contains a middle name, note that it will be split into the last name cell.

Finding the nth Character in a String

As noted above, FIND returns the position of the first match it finds. But what if you want to find the second occurrence of a particular character, or the third, or fourth?

This is possible with FIND, but we’ll need to combine it with a couple of other functions: CHAR and SUBSTITUTE.

Here’s how it works:

  • CHAR returns a character based on its ASCII code. For example, =CHAR(134) returns the dagger symbol.
  • SUBSTITUTE goes through a string and lets you swap out a character for any other one.
  • With SUBSTITUTE you can define an instance number, meaning it can swap the nth occurrence of a given string for anything else.
  • So, the idea is, we take our string, use SUBSTITUTE to swap the instance of the character we want to find for something else. We’ll use CHAR to swap it for something that is unlikely to be found in the string, then use FIND to locate that obscure substitute.

The formula looks like this:

=FIND(CHAR(134),SUBSTITUTE(D3,C3,CHAR(134),B3))

And here’s how it works in practice:

FIND the nth Character

FIND Vs SEARCH

FIND and SEARCH are very similar – they both return the position of a given character or substring within a string. However, there are some differences:

  • FIND is case sensitive but SEARCH is not
  • FIND does not allow wildcards, but SEARCH does

You can see a few examples of these differences below:

FIND vs SEARCH

FIND in Google Sheets

The FIND Function works exactly the same in Google Sheets as in Excel:

Search G Function

Additional Notes

The FIND Function is case-sensitive.

The FIND Function does not support wildcards.

Use the SEARCH Function to use wildcards and for non case-sensitive searches.

FIND Examples in VBA

You can also use the FIND function in VBA. Type:

application.worksheetfunction.find(find_text,within_text,start_num)

For the function arguments (find_text, etc.), you can either enter them directly into the function, or define variables to use instead.

Trying to convert a vbscript to php.

Have this line in the script:

digit = Application.WorksheetFunction.Find(aChar, PERMITTED)

Where aChar is a character and PERMITTED is a string.

It looks like some sort of validation, but not 100% sure.

What value will digit be? What happends if aChar is not in PERMITTED?

The documentation isn’t very clear.

Robert Harvey's user avatar

Robert Harvey

177k47 gold badges333 silver badges499 bronze badges

asked Aug 8, 2014 at 19:28

r00tAcc3ss's user avatar

4

Consider:

Sub fksdjhfsdjf()
    aChar = "a"
    PERMITTED = "qwertyasdf"
    digit = Application.WorksheetFunction.Find(aChar, PERMITTED)
    MsgBox digit
End Sub

FIND() will return the position of «a» ________________similar to InStr()

EDIT#1

Both Application.WorkSheetfunction.Find() and InStr() are case sensitive

If the little string does not exist within the big string, Application.WorkSheetfunction.Find() will raise an error and InStr() will return a 0.

This is not the same as the Range.find() Method

answered Aug 8, 2014 at 19:41

Gary's Student's user avatar

Gary’s StudentGary’s Student

95.3k9 gold badges58 silver badges98 bronze badges

3

Понравилась статья? Поделить с друзьями:
  • Worksheet word order in sentences
  • Working with function in excel
  • Worksheet vba excel свойства
  • Working with family word
  • Worksheet vba excel описание