Instrrev vba excel описание

Определение первого вхождения одной строки в другую, начиная с конца строки, с помощью функции InStrRev (VBA Excel). Синтаксис, параметры, примеры.

InStrRev – это функция, которая предназначена для определения номера позиции первого вхождения одной строки в другую, начиная с конца исходной строки.

Для поиска первого вхождения одной строки в другую с начала исходной строки используется функция InStr.

Функция InStrRev может быть незаменима при определении параметров функций Left, Mid и Right.

Синтаксис, параметры, значения

Синтаксис функции InStrRev

InstrRev(stringcheck, stringmatch, [start], [compare])

Параметры функции InStrRev

Параметр Описание Значение по умолчанию
stringcheck Обязательный аргумент. Строковое выражение, в котором выполняется поиск.
stringmatch Обязательный аргумент. Строковое выражение, которое необходимо найти.
start Необязательный аргумент. Числовое выражение, которое задает начальную позицию для поиска. -1*
compare Необязательный аргумент. Задает тип сравнения строк. 0

* Значение «-1» задает начало поиска с позиции последнего символа. Если параметр start содержит значение NULL, возникает ошибка.

Значения аргумента «compare»

Константа Значение Описание
vbUseCompareOption -1 Сравнение с помощью параметра инструкции Option Compare.
vbBinaryCompare 0 Двоичное (бинарное) сравнение.*
vbTextCompare 1 Текстовое сравнение.*
vbDatabaseCompare 2 Сравнение на основе сведений из базы данных. Только для Microsoft Access.

* При двоичном сравнении учитывается регистр букв, при текстовом – не учитывается.

Значения функции InStrRev

Если Возвращаемое значение
длина stringcheck равна 0 0
значение stringcheck равно Null Null
длина stringmatch равна 0 start
значение stringmatch равно Null Null
аргумент stringmatch не найден в аргументе stringcheck 0
аргумент stringmatch найден в аргументе stringcheck позиция первого символа найденного совпадения
start больше длины stringcheck 0

Примеры использования в VBA Excel

Пример 1

Самый простой пример:

Sub Primer1()

Dim x

x = InStrRev(«болото, плот, оплот», «лот»)

MsgBox x  ‘Результат: 17

x = InStrRev(«болото, плот, оплот», «лото»)

MsgBox x  ‘Результат: 3

End Sub

Пример 2

Пример с использованием аргумента «compare»:

Sub Primer2()

Dim x

x = InStrRev(«Болото, Плот, Оплот», «Плот»)

MsgBox x  ‘Результат: 9

x = InStrRev(«Болото, Плот, Оплот», «Плот», , 1)

MsgBox x  ‘Результат: 16

End Sub

Пример 3

Извлечение краткого имени файла из полного имени:

Sub Primer3()

Dim s, x

s = «C:UsersEvgeniyDesktopТаймер.exe»

x = InStrRev(s, ««)

s = Mid(s, x + 1)

MsgBox s  ‘Результат: Таймер.exe

End Sub


In this Article

  • InStrRev Function
    • VBA InStrRev Find Substring
    • VBA InStrRev Starting Position
    • VBA InStrRev Case Sensitivity
    • VBA InStrRev Last Space
    • VBA InStrRev Second to Last Space
    • VBA InStrRev Return Filename

This tutorial will demonstrate how to use the InStrRev VBA function to find text from the right..

InStrRev Function

The VBA InStrRev function searches for the position of a substring inside a string. It returns the position counting from left to right but it performs the search from the end of the string to the beginning.

VBA InStrRev Find Substring

The VBA InStrRev function can be used the find the position of a substring inside a string.

Sub InStrRevExample_1()
MsgBox InStrRev("ABCABC", "C")           'Result is: 6
MsgBox InStrRev("ABCABC", "BC")          'Result is: 5
MsgBox InStrRev("La La Land", "L")       'Result is: 7
MsgBox InStrRev("La La Land", "La")      'Result is: 7
MsgBox InStrRev("La La Land", "La ")     'Result is: 4
MsgBox InStrRev("La La Land", "M")       'Result is: 0
End Sub

VBA InStrRev Starting Position

VBA InStrRev Function can start the search for a substring from an assigned position counted from left to right.

Sub InStrRevExample_2()
MsgBox InStrRev("La La Land", "L")         'Result is: 7
MsgBox InStrRev("La La Land", "L", 8)      'Result is: 7
MsgBox InStrRev("La La Land", "L", 7)      'Result is: 7
MsgBox InStrRev("La La Land", "L", 6)      'Result is: 4
MsgBox InStrRev("La La Land", "L", 4)      'Result is: 4
MsgBox InStrRev("La La Land", "L", 3)      'Result is: 1
End Sub

VBA InStrRev Case Sensitivity

VBA InStrRev Function by default is case sensitive. You can change that behavior to case insensitive using an optional parameter. In that case, you must also define the starting position of the search.

Sub InStrRevExample_3()
'InstrRev by default is case sensitive
MsgBox InStrRev("La La Land", "L")     'Result is: 7
MsgBox InStrRev("La La Land", "l")     'Result is: 0

'InstrRev can perform case insensitive searches
MsgBox InStrRev("La La Land", "L", -1, vbTextCompare)     'Result is: 7
MsgBox InStrRev("La La Land", "l", -1, vbTextCompare)     'Result is: 7
End Sub

VBA InStrRev Last Space

VBA InStrRev Function can find the position of the last space in a string.

Sub InStrRevExample_4()
MsgBox InStrRev("La La Land", " ")
'Result is: 6
MsgBox InStrRev("Leonardo da Vinci", " ")
'Result is: 12
MsgBox InStrRev("May the Force be with you", " ")
'Result is: 22

End Sub

VBA InStrRev Second to Last Space

VBA InStrRev function can find the position of the second to last space in a string. We can use VBA InStrRev function to find the last space in a string and then we can use again InStrRev with a new starting point to find the position of the second to last space

Sub InStrRevExample_5()
Dim LastPos As Integer

LastPos = InStrRev("May the Force be with you", " ")
MsgBox LastPos 'Result is: 22

Dim SecondLastPos As Integer

SecondLastPos = InStrRev("May the Force be with you", " ", LastPos - 1)
MsgBox SecondLastPos 'Result is: 17
'InStrRev started the search for space just before the last space
'It will find the second to last space because it searches from right to left
End Sub

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!

automacro

Learn More

VBA InStrRev Return Filename

VBA InStrRev function can be used to easily return the filename from a string that contains the path and the filename. We will use InStrRev function with functions VBA Len and VBA Right.

VBA Len function returns the length of a string:

MsgBox Len("XBCX")      'Result is: 4

VBA Right function returns n characters from the end of a string:

MsgBox Right("ABCDE", 2)      'Result is: DE

We can use InStrRev function to find the last occurrence of “” in the pathname and use Len function to calculate the length of the filename. Right can then extract the filename.

Sub InStrRevExample_4()
Dim PathEx As String
PathEx = "C:MyFilesOtherUsefulFile.pdf"

Dim FilenameEx As String


FilenameEx = Right(PathEx, Len(PathEx) - InStrRev(PathEx, ""))
MsgBox FilenameEx 'Result is: UsefulFile.pdf

'Lets break down this code
MsgBox Len(PathEx)
'This is the length of the path name (31)


MsgBox InStrRev(PathEx, "")
'This is the position of the last  in string

MsgBox Len(PathEx) - InStrRev(PathEx, "")
'This is the length of the filename (14)
'The difference between the full length and the position of the last  in string
'(31-27=14)

'Now we know the length of the filename and of course it is at the end
'Right function is ideal for this situation
FilenameEx = Right(PathEx, Len(PathEx) - InStrRev(PathEx, ""))

End Sub

В этом учебном материале вы узнаете, как использовать Excel функцию INSTRREV с синтаксисом и примерами.

Описание

Microsoft Excel функция INSTRREV возвращает позицию первого вхождения строки в другую строку, начиная с конца строки. Это похоже на функцию INSTR, которая возвращает позицию первого вхождения, начиная с начала строки.
Функция INSTRREV — это встроенная в Excel функция, которая относится к категории строковых / текстовых функций. Её можно использовать как функцию VBA в Excel.
В качестве функции VBA вы можете использовать эту функцию в коде макроса, который вводится через редактор Microsoft Visual Basic Editor.

Синтаксис

Синтаксис функции INSTRREV в Microsoft Excel:

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

Аргументы или параметры

string
Строка для поиска.
substring
Подстрока, которую вы хотите найти.
start
Необязательно. Это начальная позиция для поиска. Если этот параметр не указан, поиск начнется с позиции -1, которая является позицией последнего символа.
compare
Необязательно. Это тип сравнения, который нужно выполнить. Это может быть одно из следующих значений:

Константа VBA Значение Пояснение
vbUseCompareOption -1 Использует опцию сравнения
vbBinaryCompare 0 Двоичное сравнение
vbTextCompare 1 Текстовое сравнение

Возвращаемое значение

Функция INSTRREV возвращает числовое значение. Если substring не найдена в string, функция INSTRREV вернет 0. Если string имеет нулевую длину, функция INSTRREV вернет 0. Если string имеет значение null, функция INSTRREV вернет null. Если start равен нулю, функция INSTRREV вернет #Error.

Применение

  • Excel для Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 для Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Тип функции

  • Функция VBA

Пример (как функция VBA)

Функцию INSTRREV можно использовать только в коде VBA в Microsoft Excel.
Давайте взглянем на некоторые примеры Excel функции INSTRREV чтобы понять, как использовать Excel функцию INSTRREV в коде Excel VBA:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

InStrRev («alphabet», «a»)

Результат: 5

InStrRev («alphabet», «a», 1)

Результат: 5

InStrRev («alphabet», «a», 1)

Результат: 1

InStrRev («alphabet», «a», 2)

Результат: 1

InStrRev («alphabet», «a», 3)

Результат: 1

InStrRev («alphabet», «a», 4)

Результат: 1

InStrRev («alphabet», «a», 5)

Результат: 5

InStrRev («alphabet», «a», 6)

Результат: 5

InStrRev («alphabet», «a», 7)

Результат: 5

InStrRev («alphabet», «a», 8)

Результат: 5

InStrRev («alphabet», «a», 9)

Результат: 0

Например:

Dim LPosition As Integer

LPosition = InStrRev («alphabet», «a»)

В этом примере переменная LPosition теперь будет содержать значение 5.

Home / VBA / Top VBA Functions / VBA INSTRREV Function (Syntax + Example)

The VBA INSTRREV function is listed under the text category of VBA functions. When you use it in a VBA code, it returns the starting position number of a sub-string (specified by you) from another string. Unlike INSTR, it starts searching for the sub-string from the right side of the string, which means the end to start.

InStrRev(StringCheck, StringMatch, [Start], [Compare])

Arguments

  • StringCheck: The string in which you want to search.
  • StringMatch: The string that you want to search for.
  • [Start]: An integer to specify the position from where you want to start the search [This is an optional argument and if omitted VBA takes 1 by default].
  • [Compare]: A string value to define the comparison to make while filtering the array [This is an optional argument and if omitted VBA takes vbBinaryCompare by default].
    • vbBinaryCompare: For binary comparison.
    • vbTextCompare: For text comparison.
    • vbDatabaseCompare: For Database Comparison. 

Example

To practically understand how to use the VBA INSTRREV function, you need to go through the below example where we have written a vba code by using it:

Sub example_INSTRREV()
Range("B1").Value = InStrRev(Range("A1"), " ")
End Sub

In the above code, we have used the INSTRREV to find the space within the value (Excel Champs) in cell A1 and it has returned 6 as a result, there’s the first space is between “Excel” and “Champs” whose position is 6.

Notes

  • If “stringcheck” or “stringmatch” is NULL then it will return NULL in the result.
  • If “stringmatch” cannot be found in “stringcheck” then will 0 is the result.

VBA InStrRev

VBA InStrRev Function

Knowing the occurrence of a string in another string can be very handy while working with day to day data. Obviously, we can do it manually by calculating the occurrence of the string in another string but that would the task very hefty. So to make it easier we have a function in VBA which is known as INSTRREV which is used to find the occurrence.

As explained above, INSTRREV in Excel VBA is used to find an occurrence of a string in another string. This function finds the first occurrence of a string in the target string and returns the value. Now we have to remember that as it gives the occurrence of the string so the returned value is numeric. Also as it is a comparison function so like other functions in VBA there are three basic comparisons methods.

Syntax of InStrRev in Excel VBA

The syntax for VBA InStrRev function in excel is as follows:

Syntax of VBA InStrRev

Now let us break down the syntax and learn about it, String is the main string from where we want to find the occurrence of a substring, Start is the numeric occurrence we provide to the string. If no start parameter is provided the function starts looking a string from the end of it. And compare is the comparison method we provide to the function. There are three types of comparison for this function:

  1. To use Option Compare which is (-1). It is also known as VbUseCompareOption.
  2. To use Binary Compare which is (0). It is also known as VbBinaryCompare.
  3. To use Text Compare which is (1). It is also known as VbTextCompare.

Again if none of the compare options is provided then the function automatically considers it as a binary compare.

Now let us use this function in a few examples and look at how to use this function.

How to Use Excel VBA InStrRev?

Now let us try with some examples on VBA InStrRev in Excel.

You can download this VBA InStrRev Excel Template here – VBA InStrRev Excel Template

Example #1 – VBA InStrRev

Let us take for an example that our string is “ I am a Good Boy” and find the occurrence of character “ “ which is space.

Step 1: Now before we move into VBA, first enable VBA then go to the code section in the developer’s section to click on visual basic.

VBA INSTRREV (Developer)

Step 2: Once we enter the VB editor we can see in the header section, there is an option of insert. Insert a new module from that option as shown below.

VBA INSTRREV (Module)

Step 3: Now let us start our subprocedure in the module as shown below.

Code:

Sub Sample()

End Sub

VBA InStrRev Example 1.1

Step 4: Now declare a variable as an integer which will hold the output value of the function for us.

Code:

Sub Sample()

Dim A As Integer

End Sub

VBA InStrRev Example 1.2

Step 5: Now in the variable use the INSTRREV function to find the occurrence of “ “ in the string “ I am a Good Boy” as follows.

Code:

Sub Sample()

Dim A As Integer
A = InStrRev(" I am a Good Boy", " ")

End Sub

VBA InStrRev Example 1.3

Step 6: Now display the value stored in variable A using the msgbox function.

Code:

Sub Sample()

Dim A As Integer
A = InStrRev(" I am a Good Boy", " ")
MsgBox A

End Sub

Example 1.4

Step 7: Let us execute the above code to get the following result.

VBA InStrRav 1

We get the result as 13 because we did not provide the start position to the function so it automatically calculated the occurrence from the end and so the result. It is found that “ “ is on the 13th position of the string when we search it from the end.

Example #2 – VBA InStrRev

In the above example, we did not provide any start position to the string. Let us provide this time in this example. Let us find out from the second position where does the “ “ occurs in the string.

Step 1: Insert a new module from that option as shown below.

VBA InStrRev Example 2.1

Step 2: Let us again define a subprocedure for our second example.

Code:

Sub Sample1()

End Sub

VBA InStrRev Example 2.2

Step 3: Declare another integer variable for the example.

Code:

Sub Sample1()

Dim A As Integer

End Sub

Example 2.3

Step 4: Now in Variable A let us find the occurrence of the “ “ from the second position using the INSTRREV function as follows.

Code:

Sub Sample1()

Dim A As Integer
A = InStrRev(" I am a Good Boy", " ", 2)

End Sub

Example 2.4

Step 5: Now use msgbox function to display the value stored in A.

Code:

Sub Sample1()

Dim A As Integer
A = InStrRev(" I am a Good Boy", " ", 2)
MsgBox A

End Sub

Example 2.6

Step 6: Now run the above code to find out the below result as shown below,

VBA InstrRev 2

We get 1 as a result as we count 2 we get I and after one position we get the occurrence of “ “.

Example #3 – VBA InStrRev

In this example let us use the compare methods. We have a string “ India is the Best” and let us find the string “E” using both text and binary compare methods.

Step 1: In the same module 1, write another subprocedure for example 3.

Code:

Sub Sample2()

End Sub

VBA InStrRev Example 3.1

Step 2: Let us define two variables as Integer which will hold the value for the occurrence of the string E in both Text and Binary comparison respectively.

Code:

Sub Sample2()

Dim A, B As Integer

End Sub

VBA InStrRev Example 3.2

Step 3: In variable A let us use the INSTRREV function with the text comparison as follows.

Code:

Sub Sample2()

Dim A, B As Integer
A = InStrRev("India is the Best", "E", , vbTextCompare)

End Sub

VBA InStrRev Example 3.3

Step 4: Now display the value stored in A using the msgbox function.

Code:

Sub Sample2()

Dim A, B As Integer
A = InStrRev("India is the Best", "E", , vbTextCompare)
MsgBox A

End Sub

VBA InStrRev Example 3.4

Step 5: In variable B let’s use the binary comparison for the same string as follows.

Code:

Sub Sample2()

Dim A, B As Integer
A = InStrRev("India is the Best", "E", , vbTextCompare)
MsgBox A
B = InStrRev("India is the Best", "E", , vbBinaryCompare)
MsgBox B

End Sub

VBA InStrRev Example 3.5

Step 6: Execute the above code to find the first result stored in variable A which is as follows.

Example 3.7

Step 7: Press OK to see the result stored in variable B.

Example 3.8

We get 0 as the result for binary compare because in our string “e” is present not “E”. In binary values both of these are different. So if a value is not found in the string we get a result as 0.

Things to Remember

  • The value returned by this function is numeric.
  • If the substring is not found the value returned is 0.
  • Start position is optional. If it is not provided, by default function search the occurrence from the end of the string.
  • The comparison methods are also optional.

Recommended Articles

This is a guide to VBA InStrRev. Here we discuss how to use Excel VBA InStrRev along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Active Cell
  2. VBA Delete Row
  3. VBA Transpose
  4. VBA RGB

Понравилась статья? Поделить с друзьями:
  • Inserting text box in word
  • Instr vba excel что это
  • Inserting tabs in word
  • Instr vba excel примеры
  • Inserting table in word