“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.)
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Application.FindFormat property (Excel) |
vbaxl10.chm133262 |
vbaxl10.chm133262 |
excel |
Excel.Application.FindFormat |
b2b62232-1f11-ec82-9344-edd39e0ae33d |
04/04/2019 |
medium |
Application.FindFormat property (Excel)
Sets or returns the search criteria for the type of cell formats to find.
Syntax
expression.FindFormat
expression A variable that represents an Application object.
Example
In this example, the search criteria is set to look for Arial, Regular, Size 10 font cells, and the user is notified.
Sub UseFindFormat() ' Establish search criteria. With Application.FindFormat.Font .Name = "Arial" .FontStyle = "Regular" .Size = 10 End With ' Notify user. With Application.FindFormat.Font MsgBox .Name & "-" & .FontStyle & "-" & .Size & _ " font is what the search criteria is set to." End With End Sub
[!includeSupport and feedback]
Метод 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 |
Несмотря на то, что в ячейке дата отображается в виде текста, ее значение хранится в ячейке в виде числа. Поэтому текстовый формат необходимо перед поиском преобразовать в формат даты.
Содержание
- Метод Range.Find (Excel)
- Синтаксис
- Параметры
- Возвращаемое значение
- Примечания
- Примеры
- Поддержка и обратная связь
- Using Find and Replace in Excel VBA
- VBA Find
- Find VBA Example
- VBA Find without Optional Parameters
- Simple Find Example
- Find Method Notes
- Nothing Found
- VBA Coding Made Easy
- Find Parameters
- After Parameter and Find Multiple Values
- LookIn Parameter
- Using the LookAt Parameter
- SearchOrder Parameter
- SearchDirection Parameter
- MatchByte Parameter
- SearchFormat Parameter
- Using Multiple Parameters
- Replace in Excel VBA
- Replace Without Optional Parameters
- Using VBA to Find or Replace Text Within a VBA Text String
- INSTR – Start
- VBA Replace Function
- VBA Code Examples Add-in
Метод Range.Find (Excel)
Находит определенные сведения в диапазоне.
Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.
Синтаксис
выражение.Find (What, After, LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, MatchByte, SearchFormat)
выражение: переменная, представляющая объект Range.
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
What | Обязательный | Variant | Искомые данные. Может быть строкой или любым типом данных Microsoft Excel. |
After | Необязательный | Variant | Ячейка, после которой нужно начать поиск. Соответствует положению активной ячейки, когда поиск выполняется из пользовательского интерфейса. |
Обратите внимание, что параметр After должен быть одной ячейкой в диапазоне. Помните, что поиск начинается после этой ячейки; указанная ячейка не входит в область поиска, пока метод не возвращается обратно в эту ячейку.
Если не указать этот аргумент, поиск начинается после ячейки в левом верхнем углу диапазона. LookIn Необязательный Variant Может быть одной из следующих констант XlFindLookIn: xlFormulas, xlValues, xlComments или xlCommentsThreaded. LookAt Необязательный Variant Может быть одной из следующих констант XlLookAt: xlWhole или xlPart. SearchOrder Необязательный Variant Может быть одной из следующих констант XlSearchOrder: xlByRows или xlByColumns. SearchDirection Необязательный Variant Может быть одной из следующих констант XlSearchDirection: xlNext или xlPrevious. MatchCase Необязательный Variant Значение True, чтобы выполнять поиск с учетом регистра. Значение по умолчанию — False. MatchByte Необязательный Variant Используется только в том случае, если выбрана или установлена поддержка двухбайтовых языков. Значение True, чтобы двухбайтовые символы сопоставлялись только с двухбайтовым символами. Значение False, чтобы двухбайтовые символы сопоставлялись с однобайтовыми эквивалентами. SearchFormat Необязательный Variant Формат поиска.
Возвращаемое значение
Объект Range, представляющий первую ячейку, в которой обнаружены требуемые сведения.
Примечания
Этот метод возвращает значение Nothing, если совпадения не найдены. Метод Find не влияет на выделенный фрагмент или активную ячейку.
Параметры для аргументов LookIn, LookAt, SearchOrder и MatchByte сохраняются при каждом использовании этого метода. Если не указать значения этих аргументов при следующем вызове метода, будут использоваться сохраненные значения. Установка этих аргументов изменяет параметры в диалоговом окне Найти, а изменение параметров в диалоговом окне Найти приводит к изменению сохраненных значений, которые используются, если опустить аргументы. Чтобы избежать проблем, устанавливайте эти аргументы явным образом при каждом использовании этого метода.
Для повторения поиска используйте методы FindNext и FindPrevious.
Когда поиск достигает конца указанного диапазона поиска, он возвращается в начало диапазона. Чтобы остановить поиск при этом возврате, сохраните адрес первой найденной ячейки, а затем проверьте адрес каждой последующей найденной ячейки, сравнив его с этим сохраненным адресом.
Чтобы найти ячейки, отвечающие более сложным шаблонам, используйте инструкцию For Each. Next с оператором Like. Например, следующий код выполняет поиск всех ячеек в диапазоне A1:C5, где используется шрифт, имя которого начинается с букв Cour. Когда Microsoft Excel находит соответствующее значение, шрифт изменяется на Times New Roman.
Примеры
В этом примере показано, как найти все ячейки в диапазоне A1:A500 на листе 1, содержащие значение 2, и изменить значение ячейки на 5. Таким образом, значения 1234 и 99299 содержали 2 и оба значения ячеек станут 5.
В этом примере показано, как найти все ячейки в диапазоне A1:A500 на листе 1, содержащие подстроку «abc», и изменить ее на «xyz».
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Using Find and Replace in Excel VBA
In this Article
This tutorial will demonstrate how to use the Find and Replace methods in Excel VBA.
VBA Find
They can be activated with the shortcuts CTRL + F (Find) or CTRL + H (Replace) or through the Ribbon: Home > Editing > Find & Select.
By clicking Options, you can see advanced search options:
You can easily access these methods using VBA.
Find VBA Example
To demonstrate the Find functionality, we created the following data set in Sheet1.
If you’d like to follow along, enter the data into your own workbook.
VBA Find without Optional Parameters
When using the VBA Find method, there are many optional parameters that you can set.
We strongly recommend defining all parameters whenever using the Find Method!
If you don’t define the optional parameters, VBA will use the currently selected parameters in Excel’s Find window. This means, you may not know what search parameters are being used when the code is ran. Find could be ran on the entire workbook or a sheet. It could search for formulas or values. There’s no way to know, unless you manually check what’s currently selected in Excel’s Find Window.
For simplicity, we will start with an example with no optional parameters defined.
Simple Find Example
Let’s look at a simple Find example:
This code searches for “employee” in the Used Range of Sheet1. If it finds “employee”, it will assign the first found range to range variable MyRange.
Next, Message Boxes will display with the address, column, and row of the found text.
In this example, the default Find settings are used (assuming they have not been changed in Excel’s Find Window):
- The search text is partially matched to the cell value (an exact cell match is not required)
- The search is not case sensitive.
- Find only searches a single worksheet
These settings can be changed with various optional parameters (discussed below).
Find Method Notes
- Find does not select the cell where the text is found. It only identifies the found range, which you can manipulate in your code.
- The Find method will only locate the first instance found.
- You can use wildcards (*) e.g. search for ‘E*’
Nothing Found
If the search text does not exist, then the range object will remain empty. This causes a major problem when your code tries to display the location values because they do not exist. This will result in an error message which you do not want.
Adding the code to our previous example:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Find Parameters
So far, we have only looked at a basic example of using the Find method. However, there are a number of optional parameters available to help you refine your search
Parameter | Type | Description | Values |
What | Required | The value to search for | Any data type such as a string or numeric |
After | Optional | Single cell reference to begin your search | Cell address |
LookIn | Optional | Use Formulas, Values, Comments for search | xlValues, xlFormulas, xlComments |
LookAt | Optional | Match part or whole of a cell | xlWhole, xlPart |
SearchOrder | Optional | The Order to search in – rows or columns | xlByRows, xlByColummns |
SearchDirection | Optional | Direction for search to go in – forward or backward | xlNext, xlPrevious |
MatchCase | Optional | Search is case sensitive or not | True or False |
MatchByte | Optional | Used only if you have installed double byte language support e.g. Chinese language | True or False |
SearchFormat | Optional | Allow searching by format of cell | True or False |
After Parameter and Find Multiple Values
You use the After parameter to specify the starting cell for your search. This is useful where there is more than one instance of the value that you are searching for.
If a search has already found one value and you know that there will be more values found, then you use the Find method with the ‘After’ parameter to record the first instance and then use that cell as the starting point for the next search.
You can use this to find multiple instances of your search text:
This code will iterate through the used range, and will display the address every time it finds an instance of ‘Light & Heat’
Note that the code will keep looping until a duplicate address is found in FindStr, in which case it will exit the Do loop.
LookIn Parameter
You can use the LookIn parameter to specify which component of the cell you want to search in. You can specify values, formulas, or comments in a cell.
- xlValues – Searches cell values (the final value of a cell after it’s calculation)
- xlFormulas – Searches within the cell formula itself (whatever is entered into the cell)
- xlComments – Searches within cell notes
- xlCommentsThreaded – Searches within cell comments
Assuming that a formula has been entered on the worksheet, you could use this example code to find the first location of any formula:
If the ‘LookIn’ parameter was set to xlValues, the code would display a ‘Not Found’ message. In this example it will return B10.
Using the LookAt Parameter
The LookAt parameter determines whether find will search for an exact cell match, or search for any cell containing the search value.
- xlWhole – Requires the entire cell to match the search value
- xlPart – Searches within a cell for the search string
This code example will locate the first cell containing the text “light”. With Lookat:=xlPart, it will return a match for “Light & Heat”.
If xlWhole was set, a match would only return if the cell value was “light”.
SearchOrder Parameter
The SearchOrder parameter dictates how the search will be carried out throughout the range.
- xlRows – Search is done row by row
- xlColumns – Search is done column by column
This influences which match will be found first.
Using the test data entered into the worksheet earlier, when the search order is columns, the located cell is A5. When the search order parameter is changed to xlRows, the located cell is C4
This is important if you have duplicate values within the search range and you want to find the first instance under a particular column name.
SearchDirection Parameter
The SearchDirection parameter dictates which direction the search will go in – effectively forward or backwards.
- xlNext – Search for next matching value in range
- xlPrevious – Search for previous matching value in range
Again, if there are duplicate values within the search range, it can have an effect on which one is found first.
Using this code on the test data, a search direction of xlPrevious will return a location of C9. Using the xlNext parameter will return a location of A4.
The Next parameter means that the search will begin in the top left-hand corner of the search range and work downwards. The Previous parameter means that the search will start in the bottom right-hand corner of the search range and work upwards.
MatchByte Parameter
The MatchBye parameter is only used for languages which use a double byte to represent each character, such as Chinese, Russian, and Japanese.
If this parameter is set to ‘True’ then Find will only match double-byte characters with double-byte characters. If the parameter is set to ‘False’, then a double-byte character will match with single or double-byte characters.
SearchFormat Parameter
The SearchFormat parameter enables you to search for matching cell formats. This could be a particular font being used, or a bold font, or a text color. Before you use this parameter, you must set the format required for the search using the Application.FindFormat property.
Here is an example of how to use it:
In this example, the FindFormat property is set to look for a bold font. The Find statement then searches for the word ‘heat’ setting the SearchFormat parameter to True so that it will only return an instance of that text if the font is bold.
In the sample worksheet data shown earlier, this will return A9, which is the only cell containing the word ‘heat’ in a bold font.
Make sure that the FindFormat property is cleared at the end of the code. If you do not your next search will still take this into account and return incorrect results.
Where you use a SearchFormat parameter, you can also use a wildcard (*) as the search value. In this case it will search for any value with a bold font:
Using Multiple Parameters
All the search parameters discussed here can be used in combination with each other if required.
For example, you could combine the ‘LookIn’ parameter with the ‘MatchCase’ parameter so that you look at the whole of the cell text, but it is case-sensitive
In this example, the code will return A4, but if we only used a part of the text e.g. ‘heat’, nothing would be found because we are matching on the whole of the cell value. Also, it would fail due to the case not matching.
Replace in Excel VBA
There is, as you may expect, a Replace function in Excel VBA, which works in a very similar way to ‘Find’ but replaces the values at the cell location found with a new value.
These are the parameters that you can use in a Replace method statement. These operate in exactly the same way as for the Find method statement. The only difference to ‘Find’ is that you need to specify a Replacement parameter.
Name | Type | Description | Values |
What | Required | The value to search for | Any data type such as a string or numeric |
Replacement | Required | The replacement string. | Any data type such as a string or numeric |
LookAt | Optional | Match part or the whole of a cell | xlPart or xlWhole |
SearchOrder | Optional | The order to search in – Rows or Columns | xlByRows or xlByColumns |
MatchCase | Optional | Search is case sensitive or not | True or False |
MatchByte | Optional | Used only if you have installed double byte language support | True or False |
SearchFormat | Optional | Allow searching by format of cell | True or False |
ReplaceFormat | Optional | The replace format for the method. | True or False |
The Replace Format parameter searches for a cell with a particular format e.g. bold in the same way the SearchFormat parameter operates in the Find method. You need to set the Application.FindFormat property first, as shown in the Find example code shown earlier
Replace Without Optional Parameters
At its simplest, you only need to specify what you are searching for and what you want to replace it with.
Note that the Find method will only return the first instance of the matched value, whereas the Replace method works through the entire range specified and replaces everything that it finds a match on.
The replacement code shown here will replace every instance of ‘Light & Heat’ with ‘L & H’ through the entire range of cells defined by the UsedRange object
Using VBA to Find or Replace Text Within a VBA Text String
The above examples work great when using VBA to interact with Excel data. However, to interact with VBA strings, you can use built-in VBA Functions like INSTR and REPLACE.
You can use the INSTR Function to locate a string of text within a longer string.
This example code will return the value of 9, which is the number position where ‘MyText’ is found in the string to be searched.
Note that it is case sensitive. If ‘MyText’ is all lower case, then a value of 0 will be returned which means that the search string was not found. Below we will discuss how to disable case-sensitivity.
INSTR – Start
There are two further optional parameters available. You can specify the start point for the search:
The start point is specified as 9 so it will still return 9. If the start point was 10, then it would return 0 (no match) as the start point would be too far forward.
INSTR – Case Sensitivity
You can also set a Compare parameter to vbBinaryCompare or vbTextCompare. If you set this parameter, the statement must have a start parameter value.
- vbBinaryCompare – Case-sensitive (Default)
- vbTextCompare – Not Case-sensitive
This statement will still return 9, even though the search text is in lower case.
To disable case-sensitivity you can also declare Option Compare Text at the top of your code module.
VBA Replace Function
If you wish to replace characters in a string with different text within your code, then the Replace method is ideal for this:
This code replaces ‘MyText’ with ‘My Text’. Note that the search string is case sensitive as a binary compare is the default.
You can also add other optional parameters:
- Start – defines position in the initial string that the replacement has to start from. Unlike in the Find method, it returns a truncated string starting from the character number defined by the Start parameter.
- Count – defines the number of replacements to be made. By default, Replace will change every instance of the search text found, but you can limit this to a single replacement by setting the Count parameter to 1
- Compare – as in the Find method you can specify a binary search or a text search using vbBinaryCompare or vbTextCompare. Binary is case sensitive and text is non case sensitive
This code returns ‘My Text string (mytext)’. This is because the start point given is 9, so the new returned string starts at character 9. Only the first ‘MyText’ has been changed because the Count parameter is set to 1.
The Replace method is ideal for solving problems like peoples’ names containing apostrophes e.g. O’Flynn. If you are using single quotes to define a string value and there is an apostrophe, this will cause an error because the code will interpret the apostrophe as the end of the string and will not recognize the remainder of the string.
You can use the Replace method to replace the apostrophe with nothing, removing it completely.
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
The Application.FindFormat
in Excel/VBA can do exactly the same as the Find-Dialog in Excel. As you can see, there is no «not equal» search in Excel for formatting, so there is no such search in VBA.
To get a list of colors and it’s usage, you will have to loop over all cells. The following code builds a dictionary of colors and it’s usage and dumps the result to the immediate window. Call it for example with ListAllColors ws.UsedRange
Sub ListAllColors(r As Range)
Dim colorList As Object
Set colorList = CreateObject("Scripting.Dictionary")
Dim cell As Range
For Each cell In r
Dim color
If cell.Interior.ColorIndex <> xlNone Then
color = cell.Interior.color
If colorList.exists(color) Then
' Color already in List, add cell to Range
Dim colorRange As Range
Set colorRange = colorList(color)
Set colorList(color) = Union(colorRange, cell)
Else
' New color, add entry to Dict
colorList.Add color, ""
' Ensure that the content is set to the cell itself, not the value.
Set colorList(color) = cell
End If
End If
Next
' Dump the result
For Each color In colorList.keys
Dim red As Long, green As Long, blue As Long
Call getRGB(CLng(color), red, green, blue)
Debug.Print color, "R:" & red, "G:" & green, "B:" & blue, colorList(color).Address
Next
End Sub
' Split color into it's red, green and blue parts
Public Sub getRGB(color As Long, ByRef red As Long, ByRef green As Long, ByRef blue As Long)
red = color And vbRed
green = (color And vbGreen) &H100
blue = (color And vbBlue) &H10000
End Sub
Update
To get a range of all colored cells, you can simplify the code, you will still have to loop over all cells, but can immediately build the union. Have a look to the following function. I added an optional parameter so you can ignore all cells with a certain color (eg vbYellow).
Function GetColoredCells(r As Range, Optional IgnoreColor As Long = -1) As Range
Dim cell As Range
For Each cell In r
Dim color
If cell.Interior.ColorIndex <> xlNone And cell.Interior.color <> IgnoreColor Then
If GetColoredCells Is Nothing Then
Set GetColoredCells = cell
Else
Set GetColoredCells = Union(GetColoredCells, cell)
End If
End If
Next
End Function
To omit the first line, call the function for example like that:
Set rg = GetColoredCells(ws.UsedRange.Offset(1, 0), vbYellow)