totn Excel Functions

MS Excel: How to use the INSTR Function (VBA)

This Excel tutorial explains how to use the Excel INSTR function with syntax and examples.

Description

The Microsoft Excel INSTR function returns the position of the first occurrence of a substring in a string.

The INSTR function is a built-in function in Excel that is categorized as a String/Text Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.

Syntax

The syntax for the INSTR function in Microsoft Excel is:

InStr( [start], string, substring, [compare] )

Parameters or Arguments

start
Optional. It is the starting position for the search. If this parameter is omitted, the search will begin at position 1.
string
The string to search within.
substring
The substring that you want to find.
compare

Optional. It is the type of comparison to perform. It can be one of the following values:

VBA Constant Value Explanation
vbUseCompareOption -1 Uses option compare
vbBinaryCompare 0 Binary comparison
vbTextCompare 1 Textual comparison

Returns

The INSTR function returns a numeric value. The first position in string is 1.
If substring is not found in string, then the INSTR function will return 0.

Note

  • When finding the location of a substring in a string, the INSTR function performs a case-sensitive search.

Applies To

  • Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Type of Function

  • VBA function (VBA)

Example (as VBA Function)

The INSTR function can only be used in VBA code in Microsoft Excel.

Let's look at some Excel INSTR function examples and explore how to use the INSTR function in Excel VBA code:

InStr("Tech on the Net", "T")
Result: 1    'Shows how start is defaulted to 1 if omitted

InStr(1, "Tech on the Net", "T")
Result: 1

InStr(1, "Tech on the Net", "t")
Result: 9    'Shows that search is case-sensitive

InStr(10, "Tech on the Net", "t")
Result: 15

InStr(1, "Tech on the Net", "the")
Result: 9

InStr(1, "Tech on the Net", "M")
Result: 0    'Shows what is returned if substring is not found

For example:

Dim LPosition As Integer

LPosition = InStr(10, "Tech on the Net", "t")

In this example, the variable called LPosition would now contain the value 15.