×

VBA Find Function

VBA Find Function

The Excel VBA FIND function finds any information in your Excel. It can be used on a Range object on the worksheet. It works the same, unlike the Excel Find & Replace option, but the only difference is VBA automates the finding process. The VBA Find function uses the same parameters in the same way. Hence, only the first parameter (the item you are searching for) is required, and rest all are optional.

We press the shortcut keyword CTRL + F while using the Find feature in Excel Workbook, and type the search value to find. It highlights all the matches, if the first value is not required, we go for the next match. If a sheet has a lot of such undesired matches, it becomes a tedious task. To combat that problem VBA, find function was introduced. It does the tasks for us and gives us the exact match, and it takes three arguments, one is what to find, where to find, and where to look at.

The settings for the optional parameters (After, LookAt, SearchOrder, and MatchByte) are saved in the cookie each time you use this method. The next time, even if you don’t specify these optional parameter values, it will automatically use the previously saved values.

Properties of Find Function are as follows:

  1. It is a member of the Range object.
  2. It searches a range of cells containing a given value or format.
  3. It is exactly the same as using the Find Dialog on an Excel worksheet.

Syntax

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

where the expression represents the range object.

Parameters

What (required) – This parameter represents the data to be searched. It can hold any string, integer, or any data type supported by Microsoft Excel.

After (optional) – This parameter represents the cell after value from where the search will begin.

Lookln (optional) - Specifies the type of data to search. The user can select one of the four options i.e., 1. xlFormulas (formulas), 2. xlValues (values), 3. xlComments (comments), or 4. xlCommentsThreaded (comments threaded).

LookAt (optional) – This parameter enables the user to specify whether a match is made against the whole of the search text or any part of the search text. It has two options: 1. xlWhole or 2. xlPart. The default value is xlWhole.

SearchOrder (optional) – This parameter represents the order in which the range is to be searched. It accepts two values, i.e., 1. xlByColumns (searches down a column), 2. xlByRows (searches across a row).

SearchDirection (optional) – This parameter signifies the search direction. It can take two values, either 1. xlNext (searches the next matching value) or 2. xlPrevious (searches the previous matching value).

MatchCase (optional) – This parameter enables or disables the case property. The Boolean True is passed to make the search case sensitive. The default value is False.

MatchByte (optional) – This parameter is used to enables or disable the double byte language support. It True is specified, it matched double-byte characters only with double-byte characters. Else for Boolean False, it matches double-byte characters with their equivalent single-byte characters. The default value is False.

SearchFormat (optional) – This parameter represents the search format to be used.

Return

This function returns the Range object of the former cell (where it finds the occurrence of the search data) if the search data is found else it returns nothing if the match is not found.

Find Function Example 1

Here, we are going to use the following Excel data.

VBA Find Function

Let’s us analyze step-step the above VBA Find function code:

Step 1: Open the developer window by using the shortcut keywords Alt +F11.

Step 2: Create a module by right-clicking on the VBA Project-> Click on Insert-> Click on Module.

VBA Find Function

Step 3: In the Module window, introduce the sub-block, followed by your macro name.

VBA Find Function

Step 4: The next step is to introduce the range and search variables.

VBA Find Function

Step 5: With the help of an input box, we will seek the search value and will store that value in the search variable (searchObj).

VBA Find Function

Step 6: By using the ‘With’ statement, we will use all the properties and methods of the Range object. So, now we will open a ‘with’ statement and will declare the range in the given sheet.

VBA Find Function

Step 7: We will define the find function and in the ‘What’ parameter will pass on the ‘searchObj’ variable and will store the return object in the ‘rangeObj’ variable.

VBA Find Function

Step 8: With the help of IF and Else block, we will enable the search found notification and will make it more user-friendly. If the match is found, it will return the range object else, it will pop a msgbox stating “Match not Found”.

VBA Find Function

Code:

Sub FindFunction_Example1()
'defining the variables
Dim rangeObj As Range
Dim searchObj As String
'defining inputbox to fetch the search value from user
searchObj = InputBox("Type the value to search")
'declaring the with block
With Sheet1.Range("A1:C10")
    'define our find function
    Set rangeObj = .Find(What:=searchObj)
    If Not rangeObj Is Nothing Then
        Application.Goto rangeObj, True
    Else
        MsgBox ("Match not found!")
    End If
End With
End Sub 

Output

Step 9: Execute the above code either by pressing the F5 shortcut key or by clicking on the Run button.

Step 10: A input box will pop up, asking for the search value. Type in the value you want to find in the excel sheet. Click on Ok.

VBA Find Function

Step 11: It will redirect the cursor to the cell address of the first occurrence of the search value found in the Excel sheet.

VBA Find Function

Step 12: Go to the VBA code, and again run the macro. In the input box type some random value that is present in the Excel sheet. Click on Ok.

VBA Find Function

Step 13: If the value is not found, a message box will pop up stating, “The match not found”.

VBA Find Function

Find Function Example 2

In the above example, the information in the Excel Sheet was unique. If Excel has to find any particular value, it will find its first occurrence and will stop if the search value is matched. What if there were duplicate data or replication of data, unlike in the given Excel datasheet.

VBA Find Function

In the above datasheet, you will notice that the name Prasant has appeared more than once. To fetch the repeated value, the ‘After’ parameter comes into play. This parameter defines cell after which reference, we want to search the data.

Let’s us analyze step-step the above VBA Find function code:

Step 1: Open the developer window by using the shortcut keywords Alt +F11. Create a module by right-clicking on the VBA Project-> Click on Insert-> Click on Module.

VBA Find Function

Step 2: In the Module window, introduce the sub-block, followed by your macro name.

VBA Find Function

Step 3: The next step is to introduce the range and search variables. With the help of an input box, we will seek the search value and will store that value in the search variable (searchObj).

VBA Find Function

Step 4: By using the ‘With’ statement, we will use all the properties and methods of the Range object. Next, we will search for the value that has been entered by the user after the A2 cell, so we define our find function as below.

VBA Find Function

Step 5: With the help of IF and Else block, we will simply the program and will make it more user-friendly. If the match is found, it will return the range object else, it will pop a msgbox stating “Match not Found”.

VBA Find Function

Code:

Sub FindFunction_Example2()
'defining the variables
Dim rangeObj As Range
Dim searchObj As String
'defining inputbox to fetch the search value from user
searchObj = InputBox("Type the value to search")
'declaring the with block
With Sheet1.Range("A1:C10")
    'define our find function with specifying What and After parameter
    Set rangeObj = .Find(What:=searchObj, After:=Range("A2"))
    If Not rangeObj Is Nothing Then
        Application.Goto rangeObj, True
    Else
        MsgBox ("Match not found!")
    End If
End With
End Sub 

Output

Step 9: Execute the above code either by pressing the F5 shortcut key or by clicking on the Run button.

Step 10: A input box will pop up, asking for the search value. Type in the value you want to find in the excel sheet. Click on Ok.

VBA Find Function

Step 11: It will redirect the cursor to the cell address of the second occurrence of the search value found in the Excel sheet.

VBA Find Function

Related Topics

Excel VBA Space Function

VBA Space Function: The Space function in VBA creates a String consisting of a specified number of spaces. Syntax Space (Number) Parameter Number (required) - This parameter represents the number of spaces. Return This function returns a...

1 minute read.

VBA Global Variable

What is Global Variable? The Global Variables in VBA refers to the variables declared before the start of any macro. They are defined outside the functions and are used by all the functions or...

6 minutes read.

Excel VBA Now Function

Excel VBA Now Function: The Now function in VBA returns the current date and time.  Syntax Now () Parameter NA Return This function returns the current date and time.  Example 1 Sub NowFunction_Example1() 'It will return...

1 minute read.

Excel VBA Replace Function

VBA Replace Function: The Replace function in VBA searches for a substring within the specified string and replaces its occurrences with a second substring. Syntax Replace (Expression, Find, Replace, [Start], [Count], [Compare]) Parameter Expression (required) – This parameter represents...

2 minutes read.

Excel VBA CVErr Function

VBA CVErr Function: The CVErr function in VBA returns an Error data type, involving with a user-specified error code. Syntax CVErr (Expression) Parameter Expression (required)- This parameter represents the required error code. Return This function returns an...

1 minute read.

Excel VBA CSng Function

VBA CSng Function: The CSng function in VBA converts the supplied expression into a single-precision floating-point number (single data type). Syntax CSng (Expression) Parameter Expression (required) – This parameter represents the expression that you want...

1 minute read.

Excel VBA Second Function

Excel VBA Second Function: The Second function in VBA returns the second element for the specified time.  Syntax Second (Time) Parameter Time (required) – This parameter represents the time. Return This function returns the second...

1 minute read.

VBA UBound

VBA UBound  The UBound or Upper Bound function in VBA is used to specify the length of an array and returns the highest subscript for a dimension for the specified array. It is...

3 minutes read.

Excel VBA ABS Function

VBA ABS Function: The ABS function in VBA returns the absolute value of the specified number. Syntax Abs (Number) Parameter Number (required) – This parameter represents the number that you want the absolute value of. Return This...

1 minute read.

Excel VBA TimeValue Function

Excel VBA TimeValue Function: The TimeValue function in VBA returns a Time from the specified String interpretation of a time /date where the date information for the given string is...

1 minute read.

CodeIgniter File Uploading Class

The Codeigniter provides a file Uploading library class which is used to upload any file such as images, pdf, mp3, etc. to the codeigniter’s application. It also allows to set various preferences such...

5 minutes read.

Excel VBA CDate Function

VBA CDate Function: The CDate function in VBA converts an expression into a Date (or Time) data type. Syntax CDate (Expression) Parameter Expression (required) - This parameter represents the expression that that you want to...

1 minute read.

Excel VBA Str Function

VBA Str Function: The Str function in VBA converts the given number into a string representation of that number. Syntax Str (Number) Parameter Number (required) – This parameter represents the numeric value that you want...

1 minute read.

CodeIgniter Architecture

Here we will understand the architecture and working of the CodeIgniter application, which helps you to elaborate all steps in simple ways. As the above image represents that whenever a request comes from the...

2 minutes read.

VBA Type Mismatch Error

What is a Type Mismatch Error? VBA Type Mismatch Error is a run time error in excel, which often occurs when the data types contained in a VBA code are not matched...

3 minutes read.

Excel VBA Time Function

Excel VBA Time Function: The Time function in VBA returns the current time. Syntax Time () Parameter NA Return This function returns the current time.  Example 1 Sub TimeFunction_Example1() ' returns the current time Dim time_val...

1 minute read.

VBA Screen Updating

What is VBA Screen Updating property? Screen Updating is a VBA property which is used to display the output generation while running the code. If this property is enabled, we could see...

6 minutes read.

Excel VBA AutoFilter

One of the reasons for Excel VBA’s popularity is its capability to filter and analyze data from huge database with the help of a method known as AutoFilter. This method permits a...

4 minutes read.

Basics of Userform

A User Form is a built-in customized dialog box that fetches data from the user through a user-friendly dialog box or window that makes up part of an application's user interface. It...

9 minutes read.

Excel Objects in VBA

What are Excel Objects? The Excel objects belong to the entities that make up an Excel Workbook, Worksheets, Columns, Rows, Cell Ranges, etc. Each object in Excel has loads of Properties that are...

6 minutes read.