I’m looking for user ID #s from a list. However some users no longer exist. I’ve tried the test
method, the on error go to
method, and if err.number<> 0 then
method. I still receive the Run-time error '91': object variable or with block variable not set
. The number does not exist on the the list. Below is my code with a couple of fruitless attempts
On Error GoTo errorLn
If Err.Number <> 0 Then
GoTo errorLn
End If
Cells.Find(What:=uSSO, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Select
What other options are there? Or am I misplacing the lines of «error»? I have tried it before and after the «cells.Find…»
asked Aug 15, 2012 at 16:03
You will want to do something different than have message boxes, presumably.
Dim myCell As Range
Set myCell = Cells.Find(What:=uSSO, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If (Not myCell Is Nothing) Then
MsgBox "something!"
Else
MsgBox "nothing"
End If
answered Aug 15, 2012 at 16:12
enderlandenderland
13.7k17 gold badges100 silver badges152 bronze badges
I believe you’ll need to restructure it just a little bit. It is not the best practice to handle errors with On Error Resume Next
, but you could try this:
On Error Resume Next
Cells.Find(What:=uSSO, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Select
If Err.Number <> 0 Then
'''Do your error stuff'''
GoTo errorLn
Else
Err.Clear
End If
Does that work for your situation?
Source: http://www.mrexcel.com/forum/excel-questions/143988-check-if-value-exists-visual-basic-applications-array.html
answered Aug 15, 2012 at 16:08
2
Try this
Sub Sample1()
Dim oSht As Worksheet
Dim uSSO As String
Dim aCell As Range
On Error GoTo Whoa
'~~> Change this to the relevant sheet
Set oSht = Sheets("Sheet1")
'~~> Set User ID here
uSSO = "User ID"
Set aCell = oSht.Cells.Find(What:=uSSO, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
'~~> Check if found or not
If Not aCell Is Nothing Then
MsgBox "Value Found in Cell " & aCell.Address
Else
MsgBox "Value Not found"
End If
Exit Sub
Whoa:
MsgBox Err.Description
End Sub
I also would recommend reading this link where I have covered .Find
and .FindNext
Topic: .Find and .FindNext In Excel VBA
Link: https://web.archive.org/web/20160316214709/https://siddharthrout.com/2011/07/14/find-and-findnext-in-excel-vba/
Kolappan N
3,4812 gold badges35 silver badges41 bronze badges
answered Aug 15, 2012 at 16:09
Siddharth RoutSiddharth Rout
146k17 gold badges206 silver badges250 bronze badges
1
Поиск какого-либо значения в ячейках 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
Метод 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:
|
LookAt | Поиск частичного или полного совпадения. Список констант xlLookAt:
|
SearchOrder | Определяет способ поиска. Список констант xlSearchOrder:
|
SearchDirection | Определяет направление поиска. Список констант xlSearchDirection:
|
MatchCase | Определяет учет регистра:
|
MatchByte | Условия поиска при использовании двухбайтовых кодировок:
|
SearchFormat | Формат поиска – используется вместе со свойством Application.FindFormat. |
* Примечания имеют две константы с одним значением. Проверяется очень просто: MsgBox xlComments
и MsgBox xlNotes
.
В справке Microsoft тип данных всех параметров, кроме SearchDirection, указан как Variant.
Знаки подстановки для поисковой фразы
Условные знаки в шаблоне поисковой фразы:
- ? – знак вопроса обозначает любой отдельный символ;
- * – звездочка обозначает любое количество любых символов, в том числе ноль символов;
- ~ – тильда ставится перед ?, * и ~, чтобы они обозначали сами себя (например, чтобы тильда в шаблоне обозначала сама себя, записать ее нужно дважды: ~~).
Простые примеры
При использовании метода Range.Find в VBA Excel необходимо учитывать следующие нюансы:
- Так как этот метод возвращает объект Range (в виде одной ячейки), присвоить его можно только объектной переменной, объявленной как Variant, Object или Range, при помощи оператора Set.
- Если поисковая фраза в заданном диапазоне найдена не будет, метод 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 |
Несмотря на то, что в ячейке дата отображается в виде текста, ее значение хранится в ячейке в виде числа. Поэтому текстовый формат необходимо перед поиском преобразовать в формат даты.
“I know well what I am fleeing from but not what I am in search of” – Michel de Montaigne
Introduction
This post covers everything you need to know about the VBA Find function. It explains, how to use Find, in simple terms. It also has tons of code examples of Find you can use right now.
If you want to go straight to an example of Find then check out How to do a Simple Find.
If you want to search for text within a string then you are looking for the InStr and InStrRev functions.
If you want to find the last row or column with data then go to Finding the Last Cell Containing Data
Download the Source Code
What is the VBA Find Function?
The Find function is very commonly used in VBA. The three most important things to know about Find are:
- The Find function is a member of Range.
- It searches a range of cells containing a given value or format.
- It is essentially the same as using the Find Dialog on an Excel worksheet.
Introduction
Excel Find Dialog
To view the Excel Find dialog, go to the Home ribbon and click on Find & Select in the Editing section. In the menu that appears select Find(shortcut is Ctrl + F)
When you do this the following dialog will appear:
The VBA Find function uses most of the options you can see on this Dialog.
How to Use Options With Find
To use the options you pass them as parameters to the Find function. This is similar to how you use worksheet functions. For example, the Sum function has a Range as a parameter. This means you give it a range when you use it.
The VBA Find uses parameters in the same way. You must give it the item you are searching for. This is the first parameter and it is required.
The rest of the parameters are optional. If you don’t use them then Find will use the existing settings. We’ll see more about this shortly.
The table in the next section shows these parameters. The sections that follow this, give examples and details of how to use these parameters.
VBA Find Parameters
The following tables shows all the Find parameters.
Parameter | Type | Description | Values |
---|---|---|---|
What | Required | The value you are searching for | Any VBA data type e.g String, Long |
After | Optional | A single cell range that you start your search from | Range(«A5») |
LookIn | Optional | What to search in e.g. Formulas, Values or Comments | xlValues, xlFormulas, xlComments |
LookAt | Optional | Look at a part or the whole of the cell | xlWhole, xlPart |
SearchOrder | Optional | The order to search | xlByRows or xlByColumns. |
SearchDirection | Optional | The direction to search | xlNext, xlPrevious |
MatchCase | Optional | If search is case sensitive | True or False |
MatchByte | Optional | Used for double byte languages | True or False |
SearchFormat | Optional | Allow searching by format. The format is set using Application.FindFormat | True or False |
Important Note about Find Parameters
Keep the following in mind as it can cause a lot of frustration when using Find.
As you can see from the table most of the VBA Find parameters are optional. As we said earlier, if you don’t set a Find parameter it uses the existing setting.
For example, if you set the LookIn parameter to xlComments, it will search for a value in comments only. The next time you run Find(either from the Dialog or from VBA) the existing LookIn setting will be Comments.
The following code shows an example of this
' Search in comments only Range("A1:A5").Find "John", LookIn:=xlComments ' Will search comments as this is the existing setting Range("A1:A5").Find "John" ' Search in formulas only Range("A1:A5").Find "John", LookIn:=xlFormulas ' Will search formulas as this is the existing setting Range("A1:A5").Find "John"
This applies to the parameters LookIn, LookAt, SearchOrder, and MatchByte.
The Find Return Value
If the search item is found then Find returns the cell with the value. That is, it returns a Range type of one cell.
If the search item is not found then Find returns an object set to Nothing.
In the following examples, you will see how to deal with the return value.
How to do a Simple Find
Let’s start with a simple example of the VBA Find. You need three things when using the Find function
- The Range to search
- The value you are searching for
- The Range to store the returned cell
Let’s take the following sample data
We are going to search for the text “Jena” in the cells A1 to A5.
The following code searches for “Jena”. When it finds “Jena”, it then places the cell in the rgFound variable.
' Find the name Jena in the range A1:A5 Dim rgFound As Range Set rgFound = Range("A1:A5").Find("Jena") ' Print cell address to Immediate Window(Ctrl + G) Debug.Print rgFound.Address
The above code shows the most basic search you can do. If this is your first time using the VBA Find function then I recommend you practice with a simple example like this.
If you want to try these examples you can download the workbook from the top of this post.
When the Value is not Found
When you use the VBA Find function, there will be times when you do not find a match. You need to handle this in your code or you will get the following error when you try to use the returned range
The following code will give this error if the text “John” is not found in the range A1 to A5
Set rgFound = Range("A1:A5").Find("John") ' Shows Error if John was not found Debug.Print rgFound.Address
What we need to do is check the return value like the following code shows
Set rgFound= Range("A1:A5").Find("John") If rgFound Is Nothing Then Debug.Print "Name was not found." Else Debug.Print "Name found in :" & rgFound.Address End If
Using After with Find
The After parameter is used if you want to start the search from a particular cell. When, the Excel Find Dialog is used, the active cell is considered the After cell. In other words, this cell is the starting point for the search. In VBA, if no After parameter is specified then the search starts at the top-left cell of the range.
Example 1 Without After
Let’s look at the following code.
Set cell = Range("A1:A6").Find("Rachal")
Find will return the cell A2 as this is where the first “Rachal” is found.
Example 2 Using After
In the next example, we use after. We are telling VBA to start the search for “Rachal” after cell A2
Set cell = Range("A1:A6").Find("Rachal", After:=Range("A2"))
This will return the cell A6
Example 3 Wrapping Around
If a match is not found then the search will “wrap around”. This means it will go back to the start of the range.
In the following example, we are looking for Drucilla. We start our search After cell A2. Find will search from A3 to A6 and then will move to A1.
So the following code will return A1 as there is no text “Drucilla” from A3 to A6:
Set cell = Range("A1:A6").Find("Drucilla", After:=Range("A2"))
The search order for this example was A4, A5, A6, A1.
You can try these example for yourself by downloading the workbook from the top of the post.
Using LookIn with Find
Using LookIn allows you to search in Values, Formulas or Comments.
Important Note: When a cell has text only, this text is considered a formula AND a value. See the table below for details
Cell Contains | Result | LookIn value is |
---|---|---|
Apple | Apple | Value and Formula |
=»App» & «le»‘ | Apple | Value only |
=LEFT(«Apple»,4)’ | Appl | Formula only |
We are going to use the following sample data.
A2 Contains “Apple” as a value only
A3 Contains “Apple” as a formula only
A4 Contains “Apple” in the comment only
The code below searches for “Apple” in the different types: value, formula, threaded comment and note.
To see a working example of this code you can download the source code from the top of this post.
' Searches in value, formula, threaded comment and note. ' https://excelmacromastery.com/excel-vba-find/ Sub UseLookIn() ' Finds A2 Dim rgFound As Range Set rgFound = shLookin.Range("A1:A5").Find("Apple", LookIn:=xlValues) Debug.Print "Found 'Apple' as value in: " & rgFound.Address ' Finds A3 Set rgFound = shLookin.Range("A1:A5").Find("Apple", LookIn:=xlFormulas) Debug.Print "Found 'Apple' as formula in: " & rgFound.Address ' Finds A4 Set rgFound = shLookin.Range("A1:A5").Find("Apple", LookIn:=xlCommentsThreaded) Debug.Print "Found 'Apple' as comment threaded in: " & rgFound.Address ' Finds A5 Set rgFound = shLookin.Range("A1:A5").Find("Apple", LookIn:=xlNotes) Debug.Print "Found 'Apple' as note in: " & rgFound.Address End Sub
Important note that I have used xlCommentsThreaded for the third one as threaded comments are used in Office 365. If you are using an older version that doesn’t have threaded comments then use xlComments.
Using LookAt with Find
Using the LookAt function is pretty straightforward.
- xlWhole means the search value must match the entire cell contents.
- xlPart means the search value only has to match part of the cell.
The following example has “Apple” as part of the cell contents in A2 and it is the full contents in cell A3.
The first Find in the following code finds “Apple” in A2. The second Find is looking for a full match so finds A3.
' https://excelmacromastery.com/ Sub UseLookAt() Dim cell As Range ' Finds A2 Set cell = Range("A1:A3").Find("Apple", Lookat:=xlPart) Debug.Print cell.Address ' Finds A3 Set cell = Range("A1:A3").Find("Apple", Lookat:=xlWhole) Debug.Print cell.Address End Sub
You can try these example for yourself by downloading the workbook from the top of the post.
Using SearchOrder with Find
The SearchOrder parameter allows us to search by row or by column. In the following sample data we have two occurrences of the text “Elli”.
If we search by row we will find the “Elli” in B2 first. This is because we search in the order row 1, then row 2 etc.
If we search by column we will find the “Elli” in A5 first. This is because we search in the order column A, the Column B etc.
The following code shows an example of using the SearchOrder with this sample data
' https://excelmacromastery.com/ Sub UseSearchOrder() Dim cell As Range ' Finds B2 Set cell = Range("A1:B6").Find("Elli", SearchOrder:=xlRows) Debug.Print cell.Address ' Finds A5 Set cell = Range("A1:B6").Find("Elli", SearchOrder:=xlColumns) Debug.Print cell.Address End Sub
Using SearchDirection with Find
SearchDirection allows you to search forward or backward. So imagine you have the range A1:A7. Searching using xlNext will go in the order
A1, A2, A3, A4, A5, A6, A7
Searching using xlPrevious will go in the order
A7, A6, A5, A4, A3, A2, A1
Using xlNext with the sample data will return A2 as this where it finds the first match. Using xlPrevious will return A6.
' NOTE: Underscore allows breaking up a line ' https://excelmacromastery.com/ Sub UseSearchDirection() Dim cell As Range ' Finds A2 Set cell = shData.Range("A1:A7") _ .Find("Elli", SearchDirection:=xlNext) Debug.Print cell.Address ' Finds A6 Set cell = shData.Range("A1:A7") _ .Find("Elli", SearchDirection:=xlPrevious) Debug.Print cell.Address End Sub
Using xlPrevious with After
It you use the After parameter with xlPrevious then it will start before from the After cell. So if we set the After cell to be A6 then the search order will be
A5,A4,A3,A2,A1,A7,A6.
The following code shows an example of this
' https://excelmacromastery.com/ Sub UseSearchDirectionAfter() Dim cell As Range ' Finds A2 Set cell = shData.Range("A1:A7").Find("Elli" _ , After:=Range("A6"), SearchDirection:=xlPrevious) Debug.Print cell.Address ' Finds A6 Set cell = shData.Range("A1:A7").Find("Elli" _ , After:=Range("A7"), SearchDirection:=xlPrevious) Debug.Print cell.Address End Sub
Using MatchCase with Find
The MatchCase parameter is used to determine if the case of the letters matters in the search. It can be set to True or False.
- True – the case of the letters must match
- False – the case of the letters does not matter
The following sample list has two entries for “Elli”. The second has a small letter e
The following code examples show the result of setting MatchCase to True and False
' https://excelmacromastery.com/ Sub UseMatchCase() Dim cell As Range ' Finds A2 Set cell = Range("A1:B6").Find("elli", MatchCase:=False) Debug.Print cell.Address ' Finds A6 Set cell = Range("A1:B6").Find("elli", MatchCase:=True) Debug.Print cell.Address End Sub
Using MatchByte with Find
The MatchByte parameter is used for languages with a double-byte character set. These are languages such as Chinese/Japanese/Korean.
If you are not using them then this parameter is not relevant. They are used as follows
- True means to match only double-byte characters with double-byte characters.
- False means to double-byte characters can match with single or double-byte characters.
Using the WildCard
We can use the asterisk symbol(*) as a wild card when searching for text. The asterisk represents one or more characters.
For example
“T*” will find any word that starts with T.
“To*” will find any word that starts with To.
“*y” will find any word that ends with y.
“*ey” will find any word that ends with ey.
The code below shows examples of using the wildcard based on this data:
' Examples of using the wild card ' https://excelmacromastery.com/excel-vba-find/ Sub WildCard() Dim rgFound As Range ' Finds Tom in A2 Set rgFound = shWildCard.Range("A1:A6").Find("T*") Debug.Print rgFound.Value & " was found in cell " & rgFound.Address ' Finds Tim in A5 Set rgFound = shWildCard.Range("A1:A6").Find("Ti*") Debug.Print rgFound.Value & " was found in cell " & rgFound.Address ' Finds Tommy in A4 Set rgFound = shWildCard.Range("A1:A6").Find("*my") Debug.Print rgFound.Value & " was found in cell " & rgFound.Address ' Finds Ellen in A3 Set rgFound = shWildCard.Range("A1:A6").Find("*len*") Debug.Print rgFound.Value & " was found in cell " & rgFound.Address ' Finds Helen in A6 Set rgFound = shWildCard.Range("A1:A6").Find("*elen*") Debug.Print rgFound.Value & " was found in cell " & rgFound.Address End Sub
Using SearchFormat with Find
Search Format is a bit different than the other parameters. It allows you to search for a cell format such as font type or cell color.
You need to set the format first by using the Application.FindFormat property. Then you set SearchFormat to True to search for this format.
In the following sample data, we have two cells formatted. Cell A5 is set to Bold and Cell A6 has the fill colour set to red.
The following code searches for the bold cell:
' Find the cell which has a bold format ' https://excelmacromastery.com/excel-vba-find/ Sub UseSearchFormat() Dim findText As String findText = "Elli" ' Clear previous formats and set new format Application.FindFormat.Clear Application.FindFormat.Font.Bold = True ' Finds A2 Dim rgFound As Range Set rgFound = Range("A1:A6").Find(findText, SearchFormat:=False) Debug.Print "Found '" & findText & "' in cell: " & rgFound.Address ' Finds A5 Set rgFound = Range("A1:A6").Find(findText, SearchFormat:=True) Debug.Print "Found '" & findText & "' in cell: " & rgFound.Address Application.FindFormat.Clear End Sub
Using Wild Card with Format
You can search for a cell based on the format only. In other words, the value in the cell is ignored in the search. You do this by placing “*” in the search string.
The following code searches for a cell that is formatted – the cell color in this example is set to red. The contents of the cell do not matter:
' Find the cell which is formatted - contents do not matter ' https://excelmacromastery.com/excel-vba-find/ Sub UseSearchFormatWild() ' Clear previous formats and set new format Application.FindFormat.Clear Application.FindFormat.Interior.Color = rgbRed ' Finds A2 as it ignores the format and finds the first cell with any contents Dim rgFound As Range Set rgFound = shSearchFormat.Range("A1:B6").Find("*", SearchFormat:=False) Debug.Print "Found format in cell: " & rgFound.Address ' Finds A5 as this is first cell with the format set to interior color as red Set rgFound = shSearchFormat.Range("A1:B6").Find("*", SearchFormat:=True) Debug.Print "Found format in cell: " & rgFound.Address Application.FindFormat.Clear End Sub
Important – Clearing Format
When you set the FindFormat attributes they remain in place until you set them again. This is something to watch out for.
For example, imagine you set the format to bold and then use Find. Then you set the format to font size 12 and use Find again. The search will look for cells where the font is bold AND of size 12.
Therefore, it is a good idea to clear the format before you use it as I have done in the above examples.
Application.FindFormat.Clear
You can see we used this in the second SearchFormat example above.
Multiple Searches
In many cases you will want to search for multiple occurrences of the same value. To do this we use the Find function first. Then we use the .FindNext function to find the next item.
.FindNext searches based on the setting we used in the Find. The following code shows a simple example of finding the first and second occurrences of the text “Elli”.
' https://excelmacromastery.com/ Sub SearchNext() Dim cell As Range ' Find first - A2 Set cell = Range("A1:A9").Find("Elli") Debug.Print "Found: " & cell.Address ' Find second - A5 Set cell = Range("A1:A9").FindNext(cell) Debug.Print "Found: " & cell.Address End Sub
Sometimes you won’t know how many occurrences there is. In this case we use a loop to keep searching until we have found all the items.
We use Find to get the first item. If we find an item we then use a Do Loop with .FindNext to find the rest of the occurrences.
FindNext will wrap around. That is, after it finds A9 it will continue the search at A1. Therefore, we store the address of the first cell we find. When FindNext returns this cell again we know we have found all the items.
The following code will find all the occurrences of Elli
' https://excelmacromastery.com/ Sub MultipleSearch() ' Get name to search Dim name As String: name = "Elli" ' Get search range Dim rgSearch As Range Set rgSearch = Range("A1:A9") Dim cell As Range Set cell = rgSearch.Find(name) ' If not found then exit If cell Is Nothing Then Debug.Print "Not found" Exit Sub End If ' Store first cell address Dim firstCellAddress As String firstCellAddress = cell.Address ' Find all cells containing Elli Do Debug.Print "Found: " & cell.Address Set cell = rgSearch.FindNext(cell) Loop While firstCellAddress <> cell.Address End Sub
The output from this code is
Found: $A$2
Found: $A$5
Found: $A$8
Finding the Last Cell Containing Data
A very common task in VBA is finding the last cell that contains data in a row or colum. This does not use the VBA Find function. Instead, we use the following code to find the last row with data
' Find the last row with data in column A LastRow = Cells(Rows.Count, 1).End(xlUp).Row ' Find the last row with data in column C LastRow = Cells(Rows.Count, 3).End(xlUp).Row
To find the last column with data we use similar code
' Find the last column with data in row 1 lLastCol = Cells(1, Columns.Count).End(xlToLeft).Column ' Find the last column with data in row 3 lLastCol = Cells(3, Columns.Count).End(xlToLeft).Column
Finding Cells with Patterns
If you want to find cells with certain patterns then you have to use the Like operator rather than Find.
For example, to find the all the names starting with E you could use the following code
' Print all names starting with the letter E ' https://excelmacromastery.com/ Sub PatternMatch() Dim cell As Range ' Go through each cell in range For Each cell In Range("A1:A20") ' Check the pattern If cell Like "[E]*" Then Debug.Print cell End If Next End Sub
To see a real-world example of using pattern matching check out Example 3: Check if a filename is valid.
An Alternative to using VBA Find
If you are expecting a large number of hits then using an array is a better option. You can read a range of cells to an array very quickly and efficiently.
The following code reads the cell values to an array and then reads through the array to count the items.
' https://excelmacromastery.com/ Sub UseArrayToCount() Dim arr As Variant ' read cell range to array arr = Sheet2.Range("A1:B25").Value Dim name As Variant, cnt As Long ' Go through the array For Each name In arr ' Count in the name 'Ray' is found If name = "Ray" Then cnt = cnt + 1 End If Next name Debug.Print "The number of occurrences was: " & cnt End Sub
Find and Replace
To do a find and Replace you can use the Replace function. It is very similar to using the Find function.
The replace function is outside the scope of this post although a lot of what you read here can be used with it. You can see the details of it at Microsoft – VBA Replace Function
What’s Next?
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)
Option ExplicitSub Test()Dim i$(1 To 6, 1 To 4), z$(1 To 53, 1 To 4), j%(1 To 6), m%(1 To 53), x%, y&Dim sht1 As Worksheet, sht2 As Worksheet On Error Resume Next Set sht1 = Sheets("Табель") Set sht2 = Sheets("Наряд") With sht1 y = .Rows(4).Find(sht2.Range("k3").Value).Column j(1) = .Columns(y).Find(What:=Range("O7"), lookat:=xlWhole, after:=.Cells(4, y)).Row j(2) = .Columns(y).Find(What:=Range("O8"), lookat:=xlWhole, after:=.Cells(4, y)).Row For x = 1 To UBound(i) i(x, 1) = .Cells(j(x), 2) Next xEnd With sht2.Range("e7").Resize(2) = i With sht1 y = .Rows(4).Find(sht2.Range("k3").Value).Column m(1) = .Columns(y).Find(What:=Range("O12"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(2) = .Columns(y).Find(What:=Range("O13"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(3) = .Columns(y).Find(What:=Range("O14"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(4) = .Columns(y).Find(What:=Range("O15"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(5) = .Columns(y).Find(What:=Range("O16"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(6) = .Columns(y).Find(What:=Range("O17"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(7) = .Columns(y).Find(What:=Range("O18"), lookat:=xlWhole, after:=.Cells(4, y)).Row m( = .Columns(y).Find(What:=Range("O19"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(9) = .Columns(y).Find(What:=Range("O20"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(10) = .Columns(y).Find(What:=Range("O21"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(11) = .Columns(y).Find(What:=Range("O22"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(12) = .Columns(y).Find(What:=Range("O23"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(13) = .Columns(y).Find(What:=Range("O24"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(14) = .Columns(y).Find(What:=Range("O25"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(15) = .Columns(y).Find(What:=Range("O26"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(16) = .Columns(y).Find(What:=Range("O27"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(17) = .Columns(y).Find(What:=Range("O28"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(18) = .Columns(y).Find(What:=Range("O29"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(19) = .Columns(y).Find(What:=Range("O30"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(20) = .Columns(y).Find(What:=Range("O31"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(21) = .Columns(y).Find(What:=Range("O32"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(22) = .Columns(y).Find(What:=Range("O33"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(23) = .Columns(y).Find(What:=Range("O34"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(24) = .Columns(y).Find(What:=Range("O35"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(25) = .Columns(y).Find(What:=Range("O36"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(26) = .Columns(y).Find(What:=Range("O37"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(27) = .Columns(y).Find(What:=Range("O38"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(28) = .Columns(y).Find(What:=Range("O39"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(29) = .Columns(y).Find(What:=Range("O40"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(30) = .Columns(y).Find(What:=Range("O41"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(31) = .Columns(y).Find(What:=Range("O42"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(32) = .Columns(y).Find(What:=Range("O43"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(33) = .Columns(y).Find(What:=Range("O44"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(34) = .Columns(y).Find(What:=Range("O45"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(35) = .Columns(y).Find(What:=Range("O46"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(36) = .Columns(y).Find(What:=Range("O47"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(37) = .Columns(y).Find(What:=Range("O48"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(38) = .Columns(y).Find(What:=Range("O49"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(39) = .Columns(y).Find(What:=Range("O50"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(40) = .Columns(y).Find(What:=Range("O51"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(41) = .Columns(y).Find(What:=Range("O52"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(42) = .Columns(y).Find(What:=Range("O53"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(43) = .Columns(y).Find(What:=Range("O54"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(44) = .Columns(y).Find(What:=Range("O55"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(45) = .Columns(y).Find(What:=Range("O56"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(46) = .Columns(y).Find(What:=Range("O57"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(47) = .Columns(y).Find(What:=Range("O58"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(48) = .Columns(y).Find(What:=Range("O59"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(49) = .Columns(y).Find(What:=Range("O60"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(50) = .Columns(y).Find(What:=Range("O61"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(51) = .Columns(y).Find(What:=Range("O62"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(52) = .Columns(y).Find(What:=Range("O63"), lookat:=xlWhole, after:=.Cells(4, y)).Row m(53) = .Columns(y).Find(What:=Range("O64"), lookat:=xlWhole, after:=.Cells(4, y)).Row For x = 1 To UBound(z) z(x, 1) = .Cells(m(x), 2) Next xEnd With sht2.Range("F12").Resize(53) = z End Sub
FIND Function of VBA Excel
The FIND function of VBA excel searches a specific value in a specified range. It looks for the first instance of such value and if a match is found, the function returns the cell containing it. However, if a match is not found, the function does not return anything. The FIND function of VBA can return either an exact or a partial match.
For example, the following code looks for the string “rose” in the range A1:A10 of “sheet1.”
With Sheets(“Sheet1”).Range(“A1:A10”)
Set Rng = .Find(What:=“rose”)
The purpose of using the FIND function in VBA is to locate the desired value in a given dataset. With a VBA code, one can automate the task of finding values in Excel. Similar to the VBA FIND, there is a “find and replace” feature in Excel too. Let us revisit the latter to understand the former.
Table of contents
- FIND Function of VBA Excel
- A Revisit to the “Find and Replace” Feature of Excel
- Syntax of the FIND function of VBA
- How to use the FIND Function of VBA Excel?
- Example #1–Return the Cell Containing the First Instance of the Search Value
- Example #2–Return the Cell Containing the Second Instance of the Search Value
- Frequently Asked Questions
- Recommended Articles
A Revisit to the “Find and Replace” Feature of Excel
In this section, the “find and replaceFind and Replace is an Excel feature that allows you to search for any text, numerical symbol, or special character not just in the current sheet but in the entire workbook. Ctrl+F is the shortcut for find, and Ctrl+H is the shortcut for find and replace.read more” dialog box of Excel has been explained briefly. The steps to find and replace a value in a worksheet are listed as follows:
Step 1: Press the keys “Ctrl+F” together to access the “find and replace” feature of Excel. Alternatively, from the “editing” group of the Home tab, click the “find & select” drop-down. Next, select the option “find.”
Step 2: The “find and replace” dialog box appears, as shown in the following image. Click “options” to see more features.
Step 3: The succeeding dialog box is displayed. This box helps find the value specified in the “find what” box. The search is subject to the following constraints:
- Within: This determines whether the search would be conducted in a worksheet or workbook.
- Search: This decides whether the search would be conducted in rows or columns.
- Look in: This decides whether the search would be conducted in formulas, values or comments of Excel.
At any point of time, one can click “options” to go back to the window shown in step 2.
Step 4: Click the “replace” option in the “find and replace” dialog box. The “replace with” option appears, as shown in the following image. This option is used when one value needs to be replaced by another.
This is how the “find and replace” feature of Excel works. Let us now return to the FIND function of VBA Excel.
Syntax of the FIND function of VBA
The syntax of the FIND function of VBA is stated as follows:
expression.Find(What, After, LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, MatchByte, SearchFormat)
The “expression” is the range object, which precedes the FIND function in a VBA code. The search range can be one or more rows, columns or the entire worksheet. The FIND function of VBA excel accepts the following arguments:
- What: This is the value to be searched. It can be numeric, textual or any other data type of Excel. This argument is the same as the “find what” option of the “find and replace” window of Excel.
- After: This indicates the cell after which the search will begin. It is entered as a single cell reference. If this argument is omitted, the search begins after the cell in the upper-left corner of the specified search range.
- LookIn: This is the place (or data) where the value needs to be searched. It can be a comment (xlComments), formula (xlFormulas) or value (xlValues). The default value of this argument is xlFormulas. Further, this argument is the same as the “look in” option of the “find and replace” window of Excel.
- LookAt: This decides whether to match the content of the entire cell (exact match) or to match a part of the cell content (partial match). The constants are xlWhole and xlPart for exact and partial matches respectively. The default value of this argument is xlPart.
- SearchOrder: This suggests the order of the search. One can specify whether the search will be in rows (xlByRows) or columns (xlByColumns). The default value of this argument is xlByRows. Further, this argument is the same as the “search” option of the “find and replace” window of Excel.
- SearchDirection: This indicates the direction in which the search will be carried out. One can search downwards or in the next cell with the constant xlNext. Alternatively, one can search backwards (upwards) or in the previous cell with the constant xlPrevious. The default value of this argument is xlNext.
- MatchCase: This decides whether the search is case-sensitive or not. If the search is case-sensitive, this argument is specified as true, otherwise it is false. The default value of this argument is false.
- MatchByte: This is used if one has installed or selected double-byte language support. It must be specified as true, if double-byte characters are to be matched with double-byte characters. It must be specified as false, if double-byte characters are to be matched with their single-byte equivalents.
- SearchFormat: This indicates whether the value to be searched should be in a specific format (like bold or italics) or not. If the search value should follow a formatting technique, this argument is specified as true, otherwise it is false. The default value of this argument is false.
Only the argument “what” is required. The rest of the arguments are optional.
The Excel VBA Find returns either of the following outcomes:
- If a match is found, the function returns the first cell where the value is located.
- If a match is not found, the function returns nothing. This is because the object of the function is set to nothing.
Alternatively, in case a match is not found, a customized message specified in the MsgBox functionVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more can be returned (refer to the code of the succeeding examples).
Note 1: The search begins after the cell specified in the “after” argument and continues till the last cell of the search range. If the value is not found till this last cell, the search begins again from the first cell of the search range till the cell specified in the “after” argument.
So, the cell specified in the “after” argument is searched at the end of the search process. For more details on the usage of the “after” argument, refer to example #2 of this article.
Note 2: Each time the FIND function of VBA is used, the settings of LookIn, LookAt, SearchOrder, and MatchByte are saved. So, if these values are omitted the next time the function is used, Excel VBA uses the previously saved values. Hence, it is recommended to explicitly state the given arguments each time search is performed by using the FIND function of VBA.
How to use the FIND Function of VBA Excel?
Let us consider some examples to understand the working of the Excel VBA Find.
You can download this VBA FIND Function Excel Template here – VBA FIND Function Excel Template
Example #1–Return the Cell Containing the First Instance of the Search Value
The following image shows some names in column A. We want to perform the following tasks in Excel VBA:
- Write a VBA code to search the first instance of the name “Aran” in column A.
- Ensure that cell A2 is selected on running the code.
Use the FIND function of VBA.
The steps to search the given name (first instance) by using the FIND function of VBA are listed as follows:
Step 1: Make sure that the Developer tabEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more is enabled in Excel. This tab will help write VBA codes. Once enabled, it will appear on the Excel ribbon, as shown in the following image.
Note: For steps related to enabling the Developer tab, click the given hyperlink.
Step 2: From the Developer tab, click “visual basic.” Next, double-click “sheet1” and a blank pane will appear on the right side.
Write the following VBA code in this pane. This is shown in the succeeding image.
Sub Sample ()
Dim FindS As String
Dim Rng As Range
FindS = InputBox (“Enter the value you want to search”)
With Sheets (“Sheet1”) .Range (“A:A”)
Explanation of the code: The given code is explained as follows:
- “Sample” is the function name given to “sub.”
- “FindS” contains the InputBox message.
- “Rng” is the variable defined for the range. In this example, the range is the entire column A (A:A).
Once the code is run, the InputBox message will appear the way it is shown in the following image. However, before running the code, let us complete it first by executing the subsequent steps.
Note: The InputBox function of VBA displays a dialog box in which the user is required to enter an input.
Step 3: Define the FIND function within the code. Notice that in the “what” argument, we have entered “findstring.” Instead, in place of “findstring,” one can enter whatever one needs to search within the defined range.
So, since “Aran” needs to be searched in column A, it can be entered in place of “findstring.” But, ensure that this name is entered within double quotes. In this way, one can specify the “what” argument of the FIND function.
Step 4: Close the function by entering the arguments (“end if,” “end with,” and “end sub”) shown in the following image.
Step 5: Save the file containing the VBA code as a macro-enabled workbook (.xlsm extension). Next, from the “run” tab, select “run sub/user form (F5).” This command runs the code.
On running the code, the succeeding dialog box appears. It shows the InputBox message that we had entered in step 2. In this box, enter the name “Aran” (with or without double quotes) and click “Ok.” Excel VBA will select cell A2, which contains the name “Aran.”
Had “sheet1” not contained the name “Aran,” Excel VBA would have returned the message “nothing found.” This message is specified in the MsgBox function of the code.
Note: By default, Excel VBA returns the first instance of the search value in the defined range. However, for Excel VBA to return cell A2, the “what” argument as well as the following dialog box, should contain the string “Aran.”
Example #2–Return the Cell Containing the Second Instance of the Search Value
The following image contains some names in the range A1:A10. Notice that the name “Aran” appears twice in column A. Write a VBA code to search and select the second instance of the name “Aran” in column A (i.e., cell A6).
Use the FIND function of VBA Excel.
The steps to search the second instance of the given name by using the FIND function of VBA are listed as follows:
Step 1: Access the Developer tab from the Excel ribbon. Click “visual basic” displayed on the left side of this tab.
From “Microsoft Excel objects,” select “Sheet2.” This is because “Sheet2” of Excel contains the dataset shown in the question of the example.
Note: For more details on customizing the ribbonRibbons in Excel 2016 are designed to help you easily locate the command you want to use. Ribbons are organized into logical groups called Tabs, each of which has its own set of functions.read more, click this hyperlink.
Step 2: Keep “sheet2” selected and from the “insert” tab, choose “module.” A blank pane appears on the right side, as shown in the following image.
Step 3: Begin to write the code in the blank pane. Define the function as “sub sample2()” and press the “Enter” key. This is the first part of the code, which is written without the double quotation marks, as shown in the following image.
Step 4: Define the variables of the code. This time “rng1” is the variable defined for range. The same is shown in the following image.
Step 5: Define the InputBox function for the “findS” variable. The InputBox message stays the way it was written in step 2 of the preceding example.
Step 6: Enter the name of the worksheet in which the FIND function needs to conduct a search. Specify the range to be searched as well. So, we enter “sheet2” and range “A:A” within double quotation marks. This is shown in the following image.
Step 7: Define the FIND function. At present, the “what” argument contains “findstring.” Since the name “Aran” is to be searched in column A, enter this name in place of “findstring.” Ensure that this name is entered within double quotes.
Further, since the second instance of the name “Aran” needs to be searched, specify the “after” argument. Enter “A2” as the “after” argument. This is because we want the search to begin after cell A2.
The arguments of the VBA FIND function are shown in the following image.
Explanation of the “after” argument: The search begins after cell A2 and continues till the last cell of column A. This is because the search range has been specified as column A (A:A).
So, since the search begins from cell A3, the value “Aran” is found in cell A6 of “Sheet2.” Hence, cell A6 will be selected by the FIND function on running the code.
Had the name “Aran” not been found from cell A3 till the last cell of column A, the search would again begin from cell A1 and end at cell A2 this time. Thus, the cell specified in the “after” argument is searched right at the end of the search process.
Step 8: Close the code by ending the “if” and “with” conditions. Close the “sub” argument by writing “end sub.” The complete code is shown in the succeeding image.
Run the code by selecting “run sub/user form (F5)” from the “run” tab of Excel VBA. The InputBox message appears asking for a value to search. When the name “Aran” is entered in this box, the outcome is the selection of cell A6. This cell contains the second instance of the name “Aran.”
Had a match not been found in the entire “sheet2,” the output would have been “nothing found.” This response is defined by the MsgBox function of the code.
Frequently Asked Questions
1. Define the FIND function of VBA Excel.
The FIND function of VBA searches for a specified value in the range defined by the user. To search, a VBA code is written by entering some or all arguments of the FIND function. One can specify the direction of search, order of search, data to be searched, the format of the search value, and so on.
The FIND function returns the cell containing the specified value. If a match is not found, the function does not return anything.
Note: For the syntax of the FIND function, refer to the heading “syntax of the FIND function of VBA” of this article.
2. How to find the last occurrence of a text string by using the FIND function of VBA?
To find the last occurrence, specify the “after” argument in the VBA code. This argument tells VBA the exact cell after which the search should begin. Note that, at a given time, a single cell reference can be supplied in this argument. It is not possible to list multiple cell references in the “after” argument.
The “after” argument is entered following the “what” argument of the FIND function. For instance, if the search range is A1:A25 and cell A20 contains the second last occurrence of the search value, the code is written as follows:
With Sheets (“Sheet4”).Range(“A1:A25”)
Set Rng = .Find(What:=“textstring”, After:=Range(“A20”))
With this code, the search for the value “textstring” begins after cell A20 in “sheet4.” The FIND function searches in the range A21:A25 and returns the last occurrence of the search value. If a match is not found in the range A21:A25, the function searches in the range A1:A20.
Note: For details related to the working of the “after” argument, refer to “note 1” of the syntax and the “explanation” in example #2 (after step 7) of this article.
3. By using the FIND function of VBA, how can one find a string by specifying some of its characters?
To find a string by specifying a part of it, either enter the LookAt argument as xlPart or omit this argument. By default, the FIND function matches the characters of the search value with the entire string. Then it returns the cell containing this entire string.
For instance, the code containing a part of a string is written as follows:
With Sheets(“Sheet4”).Range(“A1:A25”)
Set Rng = .Find(What:=”ssa”, LookAt:=xlPart)
This code searches the characters “ssa” in the range A1:A25 of “sheet4.” The cell containing the value “text message” is returned, which is called a partial match. Hence, irrespective of whether the characters of the search value are placed at the beginning, middle or end of the string, Excel VBA returns a corresponding match.
Note: The xlPart constant can be omitted from the code because it is the default value of the FIND function. But, if this argument is specified, ensure that it is not placed within double quotation marks.
Recommended Articles
This has been a complete guide to the VBA FIND function. Here we learn how to use Excel VBA FIND function with practical examples and a downloadable Excel sheet. You may also look at other articles related to Excel VBA–
- Find and Select in ExcelFind and Select in Excel is a feature available on the Home Tab of Excel that facilitates the user to quickly discover a specific text or value in the given data. The shortcut key to instantly use this feature is Ctrl+F.read more
- VBA Find NextVBA Find Next» means to continue searching for the next value from the found cell until we return to the original cell where we began the search. This is the advanced version of the «Find» method, which searches the specified value in the specified range only once.read more
- VBA IsDateThe IsDate function in VBA determines whether or not a given value is a date. The result will be «TRUE» if the supplied value or range reference value is a date value. If not, then the result is «FALSE.»read more
-
#2
Hi
Something like:
Code:
Dim rngFound As Range
Set rngFound = Sheets("WhateverSheet").UsedRange.Find(What:="SoughtValue",LookIn:=xlFormulas)
If Not rngFound Is Nothing Then
'you found the value - do whatever
Else
' you didn't find the value
End if
-
#3
That works perfectly many thanks.
-
#5
Perfect. I knew there had to be a way to do it w/out error handling. Thanks!
-
#6
How would I use this except substituting UsedRange with a user defined range such as Range(Cells(10,5), Cells(200, 5))
-
#7
I found a solution,
Set ws = Sheets(«ChooseSheet»)
With ws
Set rngFound = Range(Cells(10, 5), Cells(200, 5)).Find(What:=»Non Performers», LookIn:=xlFormulas)
End With
If Not rngFound Is Nothing Then
‘you found the value — do whatever
rngFound.Activate
rnum = ActiveCell.Row
cnum = ActiveCell.Column
Else
‘ you didn’t find the value
End If
If anyone knows (sees) a better way, please post. Humm, now if I use
Set rngFound = Sheets(«ChooseSheet»).Range(Cells(10, 5), Cells(200, 5)).Find(What:=»Non Performers», LookIn:=xlFormulas)
it seems to work. I must have had a typo but didn’t see it, sorry
-
#8
Hi All,
I have a similar requirement but when I used this code, to find the word «ERROR», it is also searching in the formula and taking action. I needed excel to check only in the outcome / result of the formula but not in the formula (contents of the formula). Could anyone please help?
Thank you in Advance,
Syed Anwar
-
#9
Hi
Did you check the parameters of the Find?
Find
In Excel Find method helps finding value in a specific range, sheet or workbook. in VBA (Visual Basic for Applications) Find method returns range object if no match found, it returns Nothing which can be used to validate response.
Syntax
expression.Find(What, After, LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, MatchByte, SearchFormat)
Parameters
- What: it is mandatory parameter and variant type which requires a string that needs to be lookup or find.
- After: its is an optional parameter and variant type where search needs to be performed after. It should be single cell range.
- LookIn: its is an optional parameter and variant type where search needs to be looked into. Look in can be down within following areas using below constants derived from XlFindLookIn Enum:
- xlFormulas: the find will take place within formula in each cell
- xlValues: the find will take place within value in each cell
- xlComments: the find will take place within comment in each cell
- xlCommentsThreaded: the find will take place within comment thread
- LookAt: its is an optional parameter and variant type which shows the lookup will happen within whole content or part of contents. LookAt can be done with the help of below constants derived from XlLookAt enum:
- xlWhole: Looked at whole contents
- xlPart: Looked at part of contents
- SearchOrder: its is an optional parameter and variant type which determines search order in a range or sheet row-wise or column-wise. There are following constants can be mapped to achieve Search Order in a Find method derived from XlSearchOrder enum:
- xlByRows: search will happen row by row
- xlByColumns: search will happen column by column
- SearchDirection: its is an optional parameter and variant type which determines search direction exposed by XlSearchDirection enum having following constants:
- xlNext: move search forward by following Find
- xlPrevious: perform search moving previous
- MatchCase: its is an optional parameter and variant type which can be set True or False, if True then identical match will be performed else case sensitivity will be ignored.
- MatchByte: its is an optional parameter and variant type works only dual byte language support is available in Excel. It can be set using True or False.
- SearchFormat: refers to search format, its is an optional parameter and variant type in nature.
Data source
Consider following data source where we will perform Find operation following exact match and highlight the result by setting the cell background color to Blue and show row and column number with value in a message box:
Code example
Public Sub FindExample() 'Capture selection and bind range object Dim oRange As Range Set oRange = Selection 'Object to hold find result Dim oFindResult As Range 'Perform find operation Set oFindResult = oRange.Find("Bus", LookIn:=xlValues) 'Validate result If Not oFindResult Is Nothing Then oFindResult.Interior.Color = vbBlue MsgBox "We found " & oFindResult.Value & " value at Row Number " & oFindResult.Row & " and at column number " & oFindResult.Column Else MsgBox "No match found" End If End Sub
Output
FindNext
Find will be continue to the next search when Find Next method is called in a range or sheet. Consider following data where we will find “Bus” which is repeating in the range and highlight all with Red color.
Data source
Code example
Public Sub FindNextExample() 'Capture selection and bind range object Dim oRange As Range Set oRange = Selection 'Object to hold find result Dim oFindResult As Range 'Perform find operation Set oFindResult = oRange.Find("Bus", LookIn:=xlValues) 'Validate result If Not oFindResult Is Nothing Then oFindResult.Interior.Color = vbGreen Dim CurrntRowNumber As Integer CurrntRowNumber = oFindResult.Row 'Loop through each find Do 'Perform Next find Set oFindResult = oRange.FindNext(oFindResult) 'Validate next result If Not oFindResult Is Nothing Then oFindResult.Interior.Color = vbGreen Else Exit Sub End If Loop While oFindResult.Row <> CurrntRowNumber Else MsgBox "No match found" End If End Sub
Output
FindPrevious
Search begin from Find would be continue and find the cell that matches same conditions provided to find and return Range. FindPrevious method works with Find and FindNext method.
Data source
Code example
Public Sub FindPreviousExample() 'Capture selection and bind range object Dim oRange As Range Set oRange = Selection 'Object to hold find result Dim oFindResult As Range 'Perform find operation Set oFindResult = oRange.Find("Bus", LookIn:=xlValues) If Not oFindResult Is Nothing Then Debug.Print "First match found at " & oFindResult.Address 'Find next Set oFindResult = oRange.FindNext(after:=oFindResult) If Not oFindResult Is Nothing Then Debug.Print "Second match found at " & oFindResult.Address 'Find previous Set oFindResult = oRange.FindPrevious(after:=oFindResult) If Not oFindResult Is Nothing Then Debug.Print "Previous match found at " & oFindResult.Address End If End If End If 'Cleanup Set oRange = Nothing Set oFindResult = Nothing End Sub
Output
First match found at $A$4
Second match found at $A$6
Previous match found at $A$4
Please leave your comments or queries under comment section also please do subscribe to our blogs to keep your self upto date.