- Функция InStr
- Синтаксис
- Параметры
- Возвращаемые значения
- Примечания
- Пример
- См. также
- Поддержка и обратная связь
- VBA INSTR – Find Text in a String
- INSTR Function
- Instr Example
- Instr Syntax
- Instr Start Position
- Case-Insensitive INSTR Test
- InstrRev Function
- VBA Coding Made Easy
- InString Examples
- If String Contains Substring
- Find Text String in a Cell
- Find Position of a Character in a String
- Search String for Word
- If Variable Contains String
- Instr and the Left Function
- Using Instr in Microsoft Access VBA
- VBA Code Examples Add-in
- Функция InStr
- Примеры
- InStr function
- Syntax
- Settings
- Return values
- Remarks
- Example
- See also
- Support and feedback
Функция InStr
Возвращает значение типа Variant (Long), определяющее положение первого вхождения одной строки в другую.
Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.
Синтаксис
InStr([ начало ], строка1, строка2, [ сравнение ])
В синтаксисе функции InStr используются следующие аргументы:
Часть | Описание |
---|---|
начало | Необязательно. Числовое выражение, которое задает начальную точку для поиска. Если этот аргумент опущен, поиск начинается с первого знака строки. Если аргумент начало содержит значение Null, возникает ошибка. Аргумент начало является обязательным, если задан аргумент сравнение. |
строка1 | Обязательно. Строковое выражение, поиск в котором выполняется. |
строка2 | Обязательно. Искомое строковое выражение. |
сравнение | Необязательно. Определяет тип сравнения строк. Если параметр compare имеет значение Null, возникает ошибка. Если аргумент сравнение опущен, тип сравнения определяется параметром Option Compare. Укажите допустимый LCID (код языка), чтобы использовать для сравнения правила, определяемые языковым стандартом. |
Параметры
Аргумент сравнение может принимать следующие значения:
Константа | Значение | Описание |
---|---|---|
vbUseCompareOption | –1 | Выполняется сравнение с помощью параметра оператора Option Compare. |
vbBinaryCompare | 0 | Выполняется двоичное сравнение. |
vbTextCompare | 1 | Выполняется текстовое сравнение. |
vbDatabaseCompare | 2 | Только Microsoft Access. Выполняется сравнение на основе сведений из базы данных. |
Возвращаемые значения
Если | Возвращаемое значение |
---|---|
строка1 является пустой | 0 |
строка1 равна Null | Null |
строка2 является пустой | начало |
строка2 равна Null | Null |
строка2 не найдена | 0 |
строка2 найдена в строке1 | Позиция найденного соответствия |
начало>строка2 | 0 |
Примечания
Функция InStrB используется с байтовыми данными, содержащимися в строке. Функция InStrB возвращает позицию байта, а не позицию знака первого вхождения одной строки в другую.
Пример
В данном примере функция InStr используется для получения позиции первого вхождения одной строки в другую.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
VBA INSTR – Find Text in a String
In this Article
INSTR Function
The VBA Instr Function checks if a string of text is found in another string of text. It returns 0 if the text is not found. Otherwise it returns the character position where the text is found.
The Instr Function performs exact matches. The VBA Like Operator can be used instead to perform inexact matches / pattern matching by using Wildcards.
Instr Example
The following code snippet searches the string “Look in this string” for the word “Look”. The Instr Function returns 1 because the text is found in the first position.
This second example returns 7 because the text is found starting in the 7th position:
Important! The Instr Function is case-sensitive by default. This means “look” will not match with “Look”. To make the test case-insensitive read below.
Instr Syntax
The syntax for the Instr function is as follows:
[start] (optional) – This optional argument is the starting position of the search. Enter 1 to start searching from position 1 (or leave blank). Enter 5 to start searching from position 5. Important! The INSTR function calculates the character position by counting from 1 NOT from the [start] position.
string – The string of text to search in.
substring – The string of text to find in the primary string.
[compare] (optional) – By default, Instr is case-sensitive. By setting this argument you can make Instr Case insensitive:
Argument vb Value
Instr Start Position
The Instr start position allows you to indicate the character position where you will begin your search. Keep in mind however, the Instr output will always count from 1.
Here we set the start position to 3 to skip the first B:
The result is 6 because the second B is the 6th character in the string.
Case-Insensitive INSTR Test
By default, VBA treats “L” different from “l”. In other words, VBA is case-sensitive. This is true of all text functions. To make VBA case-insensitive, set the [compare] argument to 1 or vbTextCompare.
Alternatively, you can add Option Compare Text to the top of your code module:
Option Compare Text will impact all of the code in that module. I personally place this at the top of any module that deals with text because I never care about case differences.
InstrRev Function
The Instr Function searches from the left. Instead you can search from the right using the InstrRev Function. The InstrRev Function works very similarly to the Instr function.
Just like the Instr function this will return 1 because there is only one instance of “Look” in the text. But if we add a second “Look”, you’ll see that it returns the position of the right-most “Look”:
Next we will review more Instr examples.
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!
InString Examples
If String Contains Substring
Here we will use an If statement to test if a string contains a a substring of text:
Find Text String in a Cell
You can also find a string in a cell:
Or loop through a range of cells to test if the cells contain some text:
Find Position of a Character in a String
This code will find the position of a single character in a string and assign the position to a variable:
Search String for Word
This code will search a string for a word:
If Variable Contains String
This code will test if a string variable contains a string of text:
Instr and the Left Function
Instr can be used along with other text functions like Left, Right, Len, and Mid to trim text.
With the Left function you can output the text prior to a string of text:
Using Instr in Microsoft Access VBA
All of the above examples work exactly the same in Access VBA as in Excel VBA.
To learn more, read our article: VBA text functions
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.
Функция InStr
Возвращает значение типа Variant ( Long), определяющее положение первого вхождения одной строки в другую.
Instr ([ начало, ] строка1, строка2[ , сравнение] )
Функция InStr имеет следующие аргументы:
Необязательный аргумент. Числовое выражение, которое задает начальное положение для каждого поиска. Если аргумент не задан, поиск начинается с первого символа. Если аргумент начало содержит значение NULL, возникает ошибка. Если задан аргумент сравнение, аргумент начало является обязательным.
Обязательный аргумент. Представляет собой строковое выражение, в котором выполняется поиск.
Обязательный аргумент. Искомое строковое выражение.
Необязательный аргумент. Определяет тип сравнение строк. Если сравнение имеет null, возникает ошибка. Если этот параметр опущен, тип сравнения определяется параметром сравнения. Укажите допустимый LCID (LocaleID), который будет использовать в сравнении правила для конкретного локали.
Совет: В Access 2010 построитель выражений включает функцию IntelliSense, которая указывает требуемые аргументы.
Аргумент compare может принимать следующие значения.
Выполняется сравнение с помощью параметра инструкции Option Compare.
Выполняется двоичное сравнение.
Выполняется текстовое сравнение.
Только в Microsoft Office Access 2007. Выполняется сравнение на основе сведений из базы данных.
строка1 является пустой
строка1 равна NULL
строка2 является пустой
строка2 равна NULL
строка2 не найдена
строка2 найдена в строке1
Позиция найденного соответствия
Функция InStrB используется с байтовыми данными, содержащимися в строке. Функция InStrB возвращает позицию байта, а не позицию знака первого вхождения одной строки в другую.
Примеры
Использование функции InStr в выражении. Функцию InStr можно использовать в любых выражениях. Например, если требуется определить позицию первой точки ( .) в поле, которое содержит IP-адрес (IPAddress), можно использовать функцию InStr для его поиска:
Функция InStr проверяет каждое значение в поле IPAddress и возвращает позицию первой точки. Следовательно, если значение первого октета IP-адреса равно 10., функция возвращает значение 3.
Можно использовать другие функции, использующие результат функции InStr, для извлечения значения октета IP-адреса, который предшествует первой точке, например:
В этом примере функция InStr(1,[IPAddress],».») возвращает позицию первой точки. В результате вычитания 1 определяется количество знаков, предшествующих первой точке, в данном случае — 2. Затем функция Left получает эти символы из левой части поля IPAddress, возвращая значение 10.
Использование функции InStr в коде VBA
Примечание: В примерах ниже показано, как использовать эту функцию в модуле Visual Basic для приложений (VBA). Чтобы получить дополнительные сведения о работе с VBA, выберите Справочник разработчика в раскрывающемся списке рядом с полем Поиск и введите одно или несколько слов в поле поиска.
В данном примере функция InStr используется для получения позиции первого вхождения одной строки в другую.
InStr function
Returns a Variant (Long) specifying the position of the first occurrence of one string within another.
Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.
Syntax
InStr([ start ], string1, string2, [ compare ])
The InStr function syntax has these arguments:
Part | Description |
---|---|
start | Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. If start contains Null, an error occurs. The start argument is required if compare is specified. |
string1 | Required. String expression being searched. |
string2 | Required. String expression sought. |
compare | Optional. Specifies the type of string comparison. If compare is Null, an error occurs. If compare is omitted, the Option Compare setting determines the type of comparison. Specify a valid LCID (LocaleID) to use locale-specific rules in the comparison. |
Settings
The compare argument settings are as follows.
Constant | Value | Description |
---|---|---|
vbUseCompareOption | -1 | Performs a comparison by using the setting of the Option Compare statement. |
vbBinaryCompare | 0 | Performs a binary comparison. |
vbTextCompare | 1 | Performs a textual comparison. |
vbDatabaseCompare | 2 | Microsoft Access only. Performs a comparison based on information in your database. |
Return values
If | InStr returns |
---|---|
string1 is zero-length | 0 |
string1 is Null | Null |
string2 is zero-length | start |
string2 is Null | Null |
string2 is not found | 0 |
string2 is found within string1 | Position at which match is found |
start > string2 | 0 |
Remarks
The InStrB function is used with byte data contained in a string. Instead of returning the character position of the first occurrence of one string within another, InStrB returns the byte position.
Example
This example uses the InStr function to return the position of the first occurrence of one string within another.
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.