Vba excel позиция символа в строке

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

InStr – это функция, которая предназначена для определения номера позиции первого вхождения одной строки в другую. Она возвращает значение типа Variant (Long).

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

Функция InStr часто незаменима при определении параметров функций Left, Mid и Right. Также ее можно использовать для определения наличия искомой подстроки в заданной строке.

Еще есть в VBA Excel функция InStrB, которая работает с байтовыми данными, содержащимися в строке. Она возвращает позицию байта, а не символа первого вхождения одной строки в другую. Смотрите ниже Пример 3.

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

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

Полный вариант:

InStr([start], string1, string2, [compare])

Сокращенный вариант:

Чаще всего в VBA Excel используется сокращенный вариант функции со значениями необязательных параметров по умолчанию.

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

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

* Если задан аргумент compare, аргумент start является обязательным.
** Если аргумент compare не указан, используется значение инструкции Option Compare, заданное на уровне модуля. Если инструкция Option Compare в начале модуля отсутствует, используется ее значение по умолчанию – 0 (двоичное сравнение).

Если параметр start или параметр compare содержит значение NULL, возникает ошибка.

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

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

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

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

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

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

Пример 1

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

Sub Test1()

Dim x As Variant

x = InStr(«На горе Фернандо-По, где гуляет Гиппо-по», «Фернандо»)

MsgBox x

‘Здесь x будет равен 9

End Sub

Пример 2

В этом примере, используя одинаковые строки, в которых выполняется поиск, и искомые подстроки, применим разные виды сравнения – двоичное (бинарное) и текстовое, и посмотрим на результаты.

Sub Test2()

Dim x As Variant

x = InStr(10, «На горе Фернандо-По, где гуляет Гиппо-по», «по», 0)

MsgBox x

‘Здесь x будет равен 36 (поиск с учетом регистра символов)

x = InStr(10, «На горе Фернандо-По, где гуляет Гиппо-по», «по», 1)

MsgBox x

‘Здесь x будет равен 18 (поиск без учета регистра символов)

End Sub

Обратите внимание: несмотря на то, что начало поиска мы задали с 10 символа, номер позиции первого вхождения считается с начала строки, в которой выполняется поиск.

Пример 3

В этом примере посмотрим на результаты посимвольного и побайтового сравнения, опять же используя одинаковые строки и искомые подстроки.

Sub Test3()

Dim x As Variant

x = InStr(«На горе Фернандо-По, где гуляет Гиппо-по», «гор»)

MsgBox x

‘Здесь x будет равен 4

x = InStrB(«На горе Фернандо-По, где гуляет Гиппо-по», «гор»)

MsgBox x

‘Здесь x будет равен 7

End Sub

Результат 7 при побайтовом сравнении получен для кодировки, у которой один символ составляет 2 байта.


InStr Function in Excel VBA

The VBA InStr function helps find the position of a given substring within a string. It returns the first occurrence of the substring in the form of an integer (output). A string is a series of characters or text supplied to the function in double quotation marks.

For example, the InStr can extract a substring from a sentence, apply the desired font to a particular string, find the position of a character within the string, and so on.

The VBA InStr function in excel begins searching from left to right.

Table of contents
  • InStr Function in Excel VBA
    • The Syntax of the VBA InStr Function
    • VBA InStr Examples
      • Example #1–“Start” Argument is Omitted
      • Example #2–“Start” Argument is Specified
      • Example #3–Case-sensitive Search
      • Example #4–Case-insensitive Search
      • Example #5–Advanced Level
    • Properties of VBA InStr Function
    • Frequently Asked Questions
    • Recommended Articles

VBA InStr

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA InStr (wallstreetmojo.com)

The Syntax of the VBA InStr Function

The syntax of the function is shown in the following image:

Instr Function

The function accepts the following arguments:

  • Start: This is the position from which the function begins to search. For example, if “start” is set at 3 and the character “a” is to be found in the word “Bangalore,” the output is 5.
  • String 1: This is the actual string within which the substring is to be found. For example, if the character “a” is to be found in the word “Bangalore,” “string 1” is “Bangalore.”
  • String 2: This is the substring to be found. For example, if the character “a” is to be found in the word “Bangalore,”“string 2” is “a.”
  • Compare: This is the type of comparison to be performed. The types of comparison methods are shown in the following image.

vba inStr

The three comparison methods are explained as follows:

1. vbBinaryCompare: This is a binary comparison and can be entered as zero (0). It is a case-sensitive search of the substring (string 2) in the actual string (string 1).

For example, if 0 is specified in the argument and:

a. The character “a” is to be found in the word “Bangalore,” the output is 2.

b. The character “A” is to be found in the word “Bangalore,” the output is 0. This is because the supplied string is in uppercase which is not found in “string 1.”

2. vbTextCompare: This is a textual comparison and can be entered as one (1). It is a case-insensitive search of the “string 2” in the “string 1.”

For example, if 1 is specified in the argument and:

a. The character “a” is to be found in the word “Bangalore,” the output is 2.

b. The character “A” is to be found in the word “Bangalore,” the output is 2. This is because this comparison method ignores the casing of the substring.

3. vbDatabaseCompare: This can be entered as two (2). It compares based on the information of the Microsoft Access database.

The “string 1” and “string 2” are required arguments, while “start” and “compare” are optional.

Note 1: If the “start” parameter is omitted, the default is 1, implying that the search begins from the first position.

Note 2: If the “compare” parameter is omitted, the default method is “vbBinaryCompare.”

VBA InStr Examples

You can download this VBA Instr Function Excel Template here – VBA Instr Function Excel Template

Example #1–“Start” Argument is Omitted

We have to find the position of character “a” in the word “Bangalore.”

Step 1: Enter the following code.

Sub Instr_Example1()

Dim i As Variant

i = InStr("Bangalore", "a")

MsgBox i

End Sub

Step 2: Press F5 or run the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more manually, as shown in the following image.

VBA InStr Example 1-2

Step 3: The output is 2, as shown in the following image. Hence, the character “a” is at the second position in the word “Bangalore.”

VBA Instr Example 1-2

Example #2–“Start” Argument is Specified

We have to find the position of character “a” in the word “Bangalore.” The search should begin from the third position.

Step 1: Enter the following code.

Sub Instr_Example2()

Dim i As Variant

i = InStr(3, "Bangalore", "a")

MsgBox i

End Sub

Step 2: Press F5 or run the VBA code manually, as shown in the following image. 

VBA InStr Example 2-2

Step 3: The output is 5, as shown in the following image. Since the search begins from the third letter (n), the VBA InStr function in excel ignores the first occurrence (second position) of the character “a.”

Hence, in this case, the character “a” is at the fifth position in the word “Bangalore.”

VBA Instr Example 2-2

Example #3–Case-sensitive Search

We have to find the character “A” in the word “Bangalore.”

Let us supply the compare argument “vbBinaryCompare” to the VBA InStr function.

Step 1: Enter the following code.

Sub Instr_Example3()

Dim i As Variant

i = InStr(1, "Bangalore", "A", vbBinaryCompare)

MsgBox i

End Sub

Step 2: Press F5 or run the VBA code manually, as shown in the following image. 

VBA InStr Example 3-2

Step 3: The output is 0, as shown in the following image. Since the argument “vbBinaryCompare” is supplied, the VBA InStr function in excel searches for the uppercase letter “A.”

Hence, the function returns 0 because it could not find the uppercase letter “A” in the word “Bangalore.”

VBA Instr Example 3-2

Example #4–Case-insensitive Search

We have to find the character “A” in the word “Bangalore” using the case-insensitive approach.

Let us supply the compare argument “vbTextCompare” to the VBA InStr function.

Step 1: Enter the following code.

Sub Instr_Example4()

Dim i As Variant

i = InStr(1, "Bangalore", "A", vbTextCompare)

MsgBox i

End Sub

Step 2: Press F5 or run the VBA code manually, as shown in the following image.

VBA InStr Example 4-2

Step 3: The output is 2, as shown in the following image. Since the argument “vbTextCompare” is supplied, the InStr function ignores the casing of the substring “A.”

Hence, the function returns 2 because the letter “A” or “a” is present at the second position in the word “Bangalore.”

Example 4-2

Example #5–Advanced Level

Let us consider an example of the advanced level of VBA InStr function in excel.

The succeeding image shows five worksheets in Excel with the names, “Data,” “Summary 1,” “Summary 2,” “Summary 3,” and “Summary 4.”

We want to hide all worksheets except for the sheet “Data.”

Example 5

Step 1: Enter the following code to hide all those sheets which contain the word “Summary” in their name.

Sub To_Hide_Specific_Sheet()

Dim Ws As Worksheet

For Each Ws In ActiveWorkbook.Worksheets

If InStr(Ws.Name, "Summary") > 0 Then
Ws.Visible = xlSheetVeryHidden
End If

Next Ws
'InStr function looks for word or phrase in the sheet name
'If it finds then it will be hidden
End Sub

Step 2: Press F5 or run the VBA code manually, as shown in the following image. In the output, only the sheet “Data” is visible. The remaining four sheets are hidden.

Example 5-2

Likewise, we can unhide those sheetsThere are different methods to Unhide Sheets in Excel as per the need to unhide all, all except one, multiple, or a particular worksheet. You can use Right Click, Excel Shortcut Key, or write a VBA code in Excel. read more which contain the word “Summary” in their name.

Step 1: Enter the following code to unhide all the sheets.

Sub To_UnHide_Specific_Sheet()

Dim Ws As Worksheet

For Each Ws In ActiveWorkbook.Worksheets

If InStr(Ws.Name, "Summary") > 0 Then
Ws.Visible = xlSheetVisible
End If

Next Ws
'InStr function looks for word or phrase in the sheet name
'If it finds then it will be hidden
End Sub

Step 2: Press F5 or run the VBA code manually, as shown in the following image. In the output, all the five sheets are unhidden.

Example 5-3

Properties of VBA InStr Function

The properties of the function are listed as follows:

  • It is a case-sensitive function. To eliminate this issue, supply the “compare” argument “vbTextCompare.”
  • It is a VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more and cannot be used like other in-built formulas of Excel.
  • It returns zero if it cannot find “string 2” in “string 1.”

Frequently Asked Questions

Define the VBA InStr function.

The VBA InStr function returns the position of one string within another string. This position corresponds to the first occurrence of the substring. The function returns an integer as the output. It returns zero (0) if the substring is not found within the string.

The syntax and the arguments of the function are listed as follows:

“InStr([start],string1,string2,[compare])”

Start: It specifies the position from which search should begin. The default value is 1.
String 1: It is the actual string within which the substring is to be searched.
String 2: It is the substring to be searched.
Compare: It specifies the comparison method to be used. The methods are stated as follows:
a. vbBinaryCompare or 0: It is used for a case-sensitive search of the substring within the string.
b. vbTextCompare or 1: It is used for a case-insensitive search of the substring within the string.
c. vbDatabaseCompare or 2: It is used for comparison with Microsoft Access database.

The arguments “string 1” and “string 2” are mandatory, while “start” and “compare” are optional.

What is the difference between the InStr and the InStrRev functions of VBA?

How to use the VBA InStr function in excel with wildcards?

With the usage of wildcards, the InStr function returns “true” or “false” depending on whether it has found the specified substring within the string or not.

The function supports the usage of the following wildcards:
1. Asterisk (*): It represents one or more characters of a string and works as follows:
“a*” refers to the text that begins with the character “a.”
• “*a” refers to the text that ends with the character “a.”
• “*a*” refers to the text that has the character “a” in the middle.
2. Question mark (?): It represents one character of a string and works as follows:
• “a?” refers to two characters beginning with “a.”
• “?a” refers to two characters ending with “a.”
• “?a?” refers to three characters having “a” in the middle.
Likewise, the VBA InStr function can be used with the tilde (~) as well.

Recommended Articles

This has been a guide to VBA InStr Function in Excel. Here we learn how to use the InStr function along with step by step examples and a downloadable excel template. Below you can find some useful Excel VBA articles-

  • VBA FileCopy Function
  • Excel VBA FileDialog
  • Excel VBA String Functions
  • Excel VBA SubString
  • VBA Name Worksheet

In this Article

  • Extracting a Substring
    • The VBA Left String Function
    • The VBA Right String Function
    • The VBA Mid String Function
  • Finding the Position of a Substring
    • The VBA Instr String Function
    • The VBA InstrRev String Function
  • Removing Spaces from a String
    • The VBA LTrim String Function
    • The VBA RTrim String Function
    • The VBA Trim String Function
  • VBA Case Functions
    • The VBA LCase String Function
    • The VBA UCase String Function
    • The VBA StrConv Function
  • Comparing Strings
    • The VBA StrComp Function
    • The VBA Like Operator
  • Other Useful VBA String Functions
    • The VBA Replace String Function
    • The VBA StrReverse Function
    • The VBA Len String Function

VBA has many string functions that will allow you to manipulate and work with text and strings in your code. In this tutorial, we are going to cover functions that will allow you to extract substrings from strings, remove spaces from strings, convert the case of a text or string, compare strings and other useful string functions.

The VBA Left String Function

The VBA Left Function allows you to extract a substring from a text or string starting from the left side. The syntax of the VBA Left String Function is:

Left(String, Num_of_characters) where:

  • String – The original text.
  • Num_of_characters  – An integer that specifies the number of characters to extract from the original text starting from the beginning.

The following code shows you how to use the Left String Function to extract the first four characters of the given string:

Sub UsingTheLeftStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "AutomateExcel"
valueTwo = Left(valueOne, 4)

MsgBox valueTwo

End Sub

The result is:

How to Use the Left String Function in VBA

The Left Function has extracted the first four letters of AutomateExcel, which are Auto.

The VBA Right String Function

The VBA Right Function allows you to extract a substring from a text or string starting from the right side. The syntax of the VBA Right String Function is:

Right(String, Num_of_characters) where:

  • String – The original text.
  • Num_of_characters  – An integer that specifies the number of characters to extract from the original text starting from the ending.

The following code shows you how to use the Right String Function to extract the last four characters of the string:

Sub UsingTheRightStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "AutomateExcel"
valueTwo = Right(valueOne, 4)

MsgBox valueTwo

End Sub

The result is:

Using the Right String Function in VBA

The Right Function has extracted the last four letters of AutomateExcel, which are xcel.

The VBA Mid String Function

The VBA Mid Function allows you to extract a substring from a text or string, starting from any position within the string that you specify. The syntax of the VBA Mid String Function is:

Mid(String, Starting_position, [Num_of_characters]) where:

  • String – The original text.
  • Starting_position – The position in the original text, where the function will begin to extract from.
  • Num_of_characters (Optional) – An integer that specifies the number of characters to extract from the original text beginning from the Starting_position. If blank, the MID Function will return all the characters from the Starting_position.

The following code shows you how to use the Mid String Function to extract four characters, starting from the second position or character in the string:

Sub UsingTheMidStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "AutomateExcel"
valueTwo = Mid(valueOne, 2, 4)

MsgBox valueTwo

End Sub

The result is outputted to a msgbox:

Using the Mid String Function in VBA

The Mid Function has extracted the four letters of AutomateExcel starting from the second character/position/letter which are utom.

Finding the Position of a Substring

The VBA Instr String Function

The VBA Instr Function returns the starting position of a substring within another string. This function is case-sensitive. The syntax of the VBA Instr String Function is:

Instr([Start], String, Substring, [Compare]) where:

  • Start (Optional) – This specifies the starting position for the function to search from. If blank, the default value of 1 is used.
  • String – The original text.
  • Substring– The substring within the original text that you want to find the position of.
  • Compare (Optional) – This specifies the type of comparison to make. If blank, binary comparison is used.

-vbBinaryCompare – Binary comparison (Upper and lower case are regarded as different)
-vbTextCompare – Text comparison (Upper and lower case are regarded as the same)
-vbDatabaseCompare – Database comparison (This option is used in Microsoft Access only, and is a comparison based on the database)

The following code shows you how to use the Instr String Function to determine the first occurrence of the substring “Th” within the main string:

Sub UsingTheInstrStringFunction()

Dim valueOne As String
Dim positionofSubstring As Integer

valueOne = "This is The Text "
positionofSubstring = InStr(1, valueOne, "Th")

Debug.Print positionofSubstring


End Sub

The result (outputted to the Immediate Window) is:

Using the Instr Function in VBA

The Instr Function has returned the position of the first occurrence of the substring “Th” which is 1. Note this function includes the spaces in the count.

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

The VBA InstrRev String Function

The VBA InstrRev Function returns the starting position of a substring within another string but it starts counting the position, from the end of the string. This function is case-sensitive. The syntax of the VBA InstrRev String Function is:

InstrRev(String, Substring, [Start], [Compare]) where:

  • String – The original text.
  • Substring – The substring within the original text that you want to find the position of.
  • Start (Optional) – This specifies the position to start searching from. If blank, the function starts searching from the last character.
  • Compare (Optional) – This specifies the type of comparison to make. If blank, binary comparison is used.

-vbBinaryCompare – Binary comparison (Upper and lower case are regarded as different)
-vbTextCompare – Text comparison (Upper and lower case are regarded as the same)
-vbDatabaseCompare – Database comparison (This option is used in Microsoft Access only, and is a comparison based on the database)

The following code shows you how to use the InstrRev String Function to determine the first occurrence of the substring “Th” within the main string, starting from the end of the string:

Sub UsingTheInstrRevStringFunction()

Dim valueOne As String
Dim positionofSubstring As Integer

valueOne = "This is The Text "
positionofSubstring = InStrRev(valueOne, "Th")

Debug.Print positionofSubstring

End Sub

The result is outputted to the Immediate Window:

Using The InstrRev Function in VBA

The InstrRev Function has returned the position of the first occurrence of the substring “Th”, but starting the counting from the end which is 9. Note this function includes the spaces in the count.

Removing Spaces from a String

The VBA LTrim String Function

The VBA LTrim Function removes all the leading spaces from a text or string. The syntax of the VBA LTrim String Function is:

LTrim(String) where:

  • String – The original text.

The following code shows you how to use the VBA LTrim Function to remove the leading spaces in the given string:

Sub UsingTheLTrimStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "         This is the website adddress https://www.automateexcel.com/excel/"
valueTwo = LTrim(valueOne)

MsgBox valueOne
MsgBox valueTwo

End Sub

The results are:

String With Leading Spaces

Using the LTrim String Function To Remove Leading Spaces

The LTrim Function has removed the leading spaces for valuetwo, which is shown in the second Message Box.

VBA Programming | Code Generator does work for you!

The VBA RTrim String Function

The VBA RTrim Function removes all the trailing spaces from a text or string. The syntax of the VBA RTrim String Function is:

RTrim(String) where:

  • String – The original text.

The following code shows you how to use the VBA RTrim Function to remove the trailing spaces in the given string:

Sub UsingTheRTrimStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "This is the website adddress https://www.automateexcel.com/excel/               "
valueTwo = RTrim(valueOne)

MsgBox valueOne
MsgBox valueTwo

End Sub

The results delivered are:
Message box With Trailing Spaces

Using The RTrim String Function

The RTrim Function has removed the trailing spaces for valuetwo, which is shown in the second Message Box.

The VBA Trim String Function

The VBA Trim Function removes all leading and trailing spaces from a text or string. The syntax of the VBA Trim String Function is:

Trim(String) where:

  • String – The original text.

The following code shows you how to use the VBA Trim Function to remove the leading and trailing spaces in the given string:

Sub UsingTheTrimStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "           This is the website adddress https://www.automateexcel.com/excel/             "
valueTwo = Trim(valueOne)

MsgBox valueOne
MsgBox valueTwo

End Sub

The results are:
Message box With Leading And Trailing Spaces

Using The Trim Function in VBA

The Trim Function has removed the leading and trailing spaces for valuetwo, which is shown in the second Message Box.

VBA Case Functions

The VBA LCase String Function

The VBA LCase Function converts letters in a text or string to lower case. The syntax of the VBA LCase String Function is:

LCase(String) where:

  • String – The original text.

The following code shows you how to use the LCase String Function to convert all the letters in the given string to lower case:

Sub UsingTheLCaseStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "THIS IS THE PRODUCT"
valueTwo = LCase(valueOne)

MsgBox valueTwo

End Sub

The result is:

Using The LCase Function in VBA

The LCase Function has converted all the letters in the string to lower case.

The VBA UCase String Function

The VBA UCase Function converts letters in a text or string to upper case. The syntax of the VBA UCase String Function is:

UCase(String) where:

  • String – The original text.

The following code shows you how to use the UCase String Function to convert all the letters in the given string to upper case:

Sub UsingTheUCaseStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "this is the product"
valueTwo = UCase(valueOne)

MsgBox valueTwo

End Sub

The result is:

Using The UCase Function in VBA

The UCase Function has converted all the letters in the string to upper case.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

The VBA StrConv Function

The VBA StrConv Function can convert letters in a text or string to upper case, lower case, proper case or unicode depending on type of conversion you specify.  The syntax of the VBA StrConv String Function is:

StrConv(String, Conversion, [LCID]) where:

  • String – The original text.
  • Conversion – The type of conversion that you want.
  • [LCID] (Optional) – An optional parameter that specifies the LocaleID. If blank, the system LocaleID is used.

The following code shows you how to use the StrConv String Function to convert the string to proper case:

Sub UsingTheStrConvStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "this is THE product"
valueTwo = StrConv(valueOne, vbProperCase)

MsgBox valueTwo

End Sub

The result is:

Using The StrConv Function in VBA

You specify the type of conversion you want to perform using the conversion parameter:

  • vbLowerCase converts all the letters in the text to lower case.
  • vbUpperCase converts all the letters in the text to upper case.
  • vbProperCase converts the first letter of each word in the text to upper case, while all the other letters are kept as lower case.
  • vbUnicode converts a string to unicode.
  • vbFromUnicode converts a string from unicode to the default code page of the system.

Comparing Strings

The VBA StrComp Function

The VBA StrComp String Function allows you to compare two strings. The function returns:

  • 0 if the two strings match
  • -1 if string1 is less than string2
  • 1 if string1 is greater than string2
  • A null value if either of the strings was Null

The following code shows you how to use the StrComp Function to compare two strings:

Sub UsingTheStrCompStringFunction()

Dim valueOne As String
Dim valueTwo As String
Dim resultofComparison As Integer

valueOne = "AutomateExcel"
valueTwo = "AutomateExcel"
resultofComparison = StrComp(valueOne, valueTwo)
Debug.Print resultofComparison

End Sub

The result is:

Using The StrComp Function in VBA

The StrComp Function has found an exact match between the two strings and returned 0.

The VBA Like Operator

The VBA Like Operator allows you to compare a text or string to a pattern and see if there is a match. You would usually use the Like Operator in conjunction with wildcards. The following code shows you how to use the Like Operator:

Sub UsingTheLikeOperatorInVBA()

Dim valueOne As String
valueOne = "Let's view the output"

If valueOne Like "*view*" Then
MsgBox "There is a match, this string contains the word view"
Else
MsgBox "No match was found"
End If

End Sub

The result is:

Using The Like Operator in VBA

The wildcards you can use with the Like Operator to find pattern matches include:

  • ? which matches a single character
  • # which matches a single digit
  • * which matches zero or more characters

The following code shows you how you would use the Like Operator and the ? wildcard to match a pattern in your code:

Sub UsingTheLikeOperatorWithAWildcardInVBA()

Dim valueOne As String
valueOne = "The"

If valueOne Like "??e" Then
MsgBox "There is a match, a matching pattern was found"
Else
MsgBox "No match was found"
End If

End Sub

The result delivered is:
Using The Like Operator To Match Patterns in VBA

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Other Useful VBA String Functions

The VBA Replace String Function

The VBA Replace Function replaces a set of characters in a string with another set of characters. The syntax of the VBA Replace String Function is:

Replace(String, Find, Replace, [Start], [Count], [Compare]) where:

  • String – The original text.
  • Find – The substring to search for within the original text.
  • Replace – The substring to replace the Find substring with.
  • Start (Optional) – The position to begin searching from within the original text. If blank, the value of 1 is used and the function starts at the first character position.
  • Count (Optional) – The number of occurrences of the Find substring in the original text to replace. If blank, all the occurrences of the Find substring are replaced.
  • Compare (Optional) – This specifies the type of comparison to make. If blank, binary comparison is used.

    -vbBinaryCompare – Binary comparison
    -vbTextCompare – Text comparison
    -vbDatabaseCompare – Database comparison (This option is used in Microsoft Access only, and is a comparison based on the database.)

The following code shows you how to use the Replace String Function:

Sub UsingTheReplaceStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "ProductABC"
valueTwo = Replace(valueOne, "ABC", "XYZ")

MsgBox valueTwo

End Sub

The result is:

Using The Replace String Function in VBA

The Replace Function found the substring ABC within ProductABC and replaced it with the substring XYZ.

The VBA StrReverse Function

The VBA StrReverse Function reverses the characters in a given text or string. The syntax of the VBA StrReverse String Function is:

StrReverse(String) where:

  • String – The original text.

The following code shows you how to use the VBA StrReverse Function to reverse the characters in the string Product:

Sub UsingTheStrReverseStringFunction()

Dim valueOne As String
Dim valueTwo As String

valueOne = "Product"
valueTwo = StrReverse(valueOne)

MsgBox valueTwo

End Sub

The result is:

Using The StrReverse Function in VBA

The VBA Len String Function

The VBA Len Function returns the number of characters in a text string. The syntax of the VBA Len String Function is:

Len(String) where:

  • String – The original text.

The following code shows you how to use the Len String Function to determine the length of the string AutomateExcel:

Sub UsingTheLenFunction()

Dim valueOne As String
Dim stringLength As Integer

valueOne = "AutomateExcel"
stringLength = Len(valueOne)
Debug.Print stringLength


End Sub

The result is:

Using The Len String Function in VBA

The Len Function has counted all the characters in the text AutomateExcel, which is 13 letters.

VBA InStr function in Excel is categorized as a Text/String function in VBA. It is a built-in function in MS Office Excel. Finds the position of specified sub-string with the given string. Returns the first occurrence position as a integer value. If it doesn’t find specified sub string, It returns a value ‘0’. Performs a case sensitive search. It has four parameters.

The VBA InStr function use in either procedure or function in a VBA editor window in Excel. We can use this VBA InStr function any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the InStr function, where we can use this VBA InStr function and real-time examples.

Table of Contents:

  • Overview
  • Syntax of VBA InStr Function in Excel:
  • Parameters or Arguments:
  • Where we can apply or use the InStr Function?
  • Example 1: Search specified substring in given string, starting at position 1
  • Example 2: Search specified substring within string, starting at position 3
  • Example 3: InStr Function using ‘vbBinaryCompare’ (Case Sensitive Search)
  • Example 4: InStr Function using vbTextCompare (Avoid Case Sensitive Search)
  • Example 5: Search for ‘@’ symbol in specified email
  • Example 6: Search for ‘.’ and file extension within specified file name
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the VBA InStr function is

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

In the above syntax the second and third arguments are mandatory (string & substring) parameters. And the first and last two parameters are optional (start & compare) Arguments.

Parameters or Arguments:

Where
Start: The start is an optional argument, and its default value is ‘1’. It represents the starting position for the search. It accepts integer type input value. If we don’t specify any value, default it considers default value as one.
String: The string is a mandatory argument. The string in which we want to search.
Substring: The substring is a mandatory argument. The substring that you want to find within string.
Compare: The compare is an optional argument. It represents which type of comparison needs to perform. It has four numeric values. It we don’t specify any value, default it considers a binary comparison. Here are the different four comparisons, which are shown in the below table.

VBA Compare Value Explanation
vbUseCompareOption -1 Performs a comparision using the ‘option compare’
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.

Where we can apply or use the VBA InStr Function in Excel?

We can use this VBA InStr function in MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Search specified substring in given string, starting at position 1

Here is a simple example of the VBA InStr function. This below example macro uses the InStr function and finds specified substring in within given string, starting at position 1

'Search for "if" in string "Life is Beautiful", starting at position 1.
Sub VBA_InStr_Function_Ex1()
    
    'Variable declaration
    Dim iPosition As Integer
    Dim sWord As String
    
    sWord = "Life is Beautiful"
    
    'Search for 'if' in given string
    iPosition = InStr(1, sWord, "if")
    'or
    iPosition = InStr(sWord, "if")
        
    'You can see answer in the Worksheet
    Sheets("VBAF1.com").Range("F8") = "The text 'if' position : " & iPosition
    
    'Display output message
    MsgBox "The text 'if' position: " & iPosition, vbInformation, "Example of InStr Function"
    
End Sub

In the above example ‘iPosition & sWord’ are declared as an integer and string data type. This variable ‘iPosition’ now contains the starting position of substring.
Output: Here is the screen shot of first example output.
VBA InStr Function

Example 2: Search specified substring within string, starting at position 3

Here is another example of the VBA InStr function. This below example macro uses the InStr function and finds specified substring in within given string, starting at position 3

'Search for "if" in string "Life is Beautiful", starting at position 3.
Sub VBA_InStr_Function_Ex2()
    
    'Variable declaration
    Dim iPosition As Integer
    Dim sWord As String
    
    sWord = "Life is Beautiful"
    
    'Search for 'if' in given string
    iPosition = InStr(3, sWord, "if")
        
    'You can see answer in the Worksheet
    Sheets("VBAF1.com").Range("F11") = "The text 'if' position : " & iPosition
    
    'Display output message
    MsgBox "The text 'if' position : " & iPosition, vbInformation, "Example of InStr Function"
    
End Sub

Output: Here is the screen shot of second example output.
VBA InStr Function

Example 3: InStr Function using ‘vbBinaryCompare’ (Case Sensitive Search)

Here is a simple example of the VBA InStr function. This below example macro uses the InStr function and finds ‘b’ substring in within given string, starting at position 1. Where ‘b’ is a small letter. It returns ‘0’ as an output. Notice fourth argument in InStr function. It performs a binary comparison.

'Search for "b" in string "Life is Beautiful", starting at position 1.
Sub VBA_InStr_Function_Ex3()
    
    'Variable declaration
    Dim iPosition As Integer
    Dim sWord As String
    
    sWord = "Life is Beautiful"
    
    'Search for 'b' in given string
    iPosition = InStr(1, sWord, "b")
    ‘or
   ‘iPosition =InStr(1, sWord, "b", vbBinaryCompare)

        
    'You can see answer in the Worksheet
    Sheets("VBAF1.com").Range("F14") = "The text 'b' position : " & iPosition
    
    'Display output message
    MsgBox "The text 'b' position : " & iPosition, vbInformation, "Example of InStr Function"
    
End Sub

Note: VBA InStr is a Case sensitive search.
Output: Here is the screen shot of third example output.
VBA InStr Function

Example 4: InStr Function using vbTextCompare (Avoid Case Sensitive Search)

Here is one more example of the VBA InStr function. This below example macro uses the InStr function and finds ‘b’ substring in within given string, starting at position 1. Where ‘b’ is a small letter, but It avoids case sensitive search and returns ‘9’ as an output. Notice fourth argument in InStr function. It performs a textual comparison.

'Search for "b" in string "Life is Beautiful", starting at position 1.
Sub VBA_InStr_Function_Ex4()
    
    'Variable declaration
    Dim iPosition As Integer
    Dim sWord As String
    
    sWord = "Life is Beautiful"
    
    'Search for 'b' in given string
    iPosition = InStr(1, sWord, "b", vbTextCompare)
        
    'You can see answer in the Worksheet
    Sheets("VBAF1.com").Range("F17") = "The text 'b' position : " & iPosition
    
    'Display output message
    MsgBox "The text 'b' position : " & iPosition, vbInformation, "Example of InStr Function"
    
End Sub

Output: Here is the screen shot of fourth example output.
VBA InStr Function

Example 5: Search for ‘@’ symbol in specified email

Here is a simple example of the VBA InStr function. This below example macro uses the InStr function and finds specified substring in within given string, starting at position 1. We can also search special characters within string. Sometimes we want to search ‘@’ position in email. Let’s see.

'Search for "@" in string "abcde@gmail.com", starting at position 1.
Sub VBA_InStr_Function_Ex5()
    
    'Variable declaration
    Dim iPosition As Integer
    Dim sWord As String
    
    sWord = "abcde@gmail.com"
    
    'Searh for '@' in given string
    iPosition = InStr(1, sWord, "@")
        
    'You can see answer in the Worksheet
    Sheets("VBAF1.com").Range("I8") = "The Special Character '@' position : " & iPosition
    
    'Display output message
    MsgBox "The Special Character '@' position : " & iPosition, vbInformation, "Example of InStr Function"
    
End Sub

Output: Here is the screen shot of fifth example output.
VBA InStr Function

Example 6: Search for ‘.’ and file extension within specified file name

Here is a simple example of the VBA InStr function. This below example macro uses the InStr function and finds specified substring(.) in within given string, starting at position 1. Most of the time while writing VBA codes we try to extract file extension or file name. Before that we need to identify ‘.’ Position In file name.

'Search for '.' and file extension in the file name "xyz.xlsm"
Sub VBA_InStr_Function_Ex6()
    
    'Variable declarations
    Dim iPosition As Integer
    Dim sWord As String
    Dim sFileExtn As String
    
    sWord = "xyz.xlsm"
    
    'Search file extension in given string
    iPosition = InStr(1, sWord, ".")
    
    'Get File Extension
    sFileExtn = Right(sWord, Len(sWord) - iPosition)
        
    'You can see answer in the Worksheet
    Sheets("VBAF1.com").Range("I11") = "Specified File Extension is : " & sFileExtn
    
    'Display output message
    MsgBox "Specified File Extension is : " & sFileExtn, vbInformation, "Example of InStr Function"
    
End Sub

Output: Here is the screen shot of sixth example output.
VBA InStr Function

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Yesterday, I got an email from one of my readers – June.

She wanted to know how to apply bold font format to a specific part of a string within a cell. For example, apply the bold format to only the word ‘Hello’ from ‘Hello World’.

And she wanted to do this for hundreds of cell at once.

Since there is no inbuilt functionality in Excel that can do that, I created a simple macro that uses the Excel VBA InStr function (you will see how to do this in Example 4 in this tutorial).

But first, let’s see how the Excel VBA InStr function works!

Excel VBA InStr Function

In this tutorial, I will explain the usage of InStr function in Excel VBA and see some practical examples where it can be used.

Excel VBA InStr Function – Introduction

InStr function finds the position of a specified substring within the string and returns the first position of its occurrence.

For example, if you want to find the position of ‘x’ in ‘Excel’, using the Excel VBA InStr function would return 2.

Syntax of InStr Function

InStr( [Start], String1, String2, [Compare] )
  • [Start] – (optional argument) this is an integer value that tells the InStr function the starting position from which it should start looking. For example, if I want the search to start from the beginning, I will enter the value as 1. If I want it to begin with the third character onwards, I will use 3. If omitted, the default value of 1 is taken.
  • String1 – This is the main string (or the parent string) in which you want to search. For example, if you’re looking for the position of x in Excel, String 1 would be “Excel”.
  • String2 – This is the substring that you are searching for. For example, if you’re looking for the position of x in Excel, String2 would be x.
  • [Compare] – (optional argument) You can specify one the following three values for [compare] argument:
    • vbBinaryCompare – This would do a character by character comparison. For example, if you’re looking for ‘x’ in ‘Excel’, it will return 2, but if you’re looking for ‘X’ in ‘Excel’, it will return 0 as X is in upper case. You can also use 0 instead of vbBinaryCompare. If the [Compare] argument is omitted, this is the taken as default.
    • vbTextCompare – This would do a textual comparison. For example, if you look for ‘x’ or ‘X’ in Excel, it would return 2 in both the cases. This argument ignores the letter case. You can also use 1 instead of vbTextCompare.
    • vbDatabaseCompare –  This is used for Microsoft Access only.  It uses the information in the database to perform the comparison. You can also use 2 instead of vbDatabaseCompare.

Additional Notes on Excel VBA InStr Function:

  • InStr is a VBA function and not a worksheet function. This means that you can not use it within the worksheet.
  • If String2 (which is the substring whose position you’re looking for) is empty, the function would return the value of the [Start] argument.
  • If the InStr function can not find the substring within the main string, it would return 0.

Now let’s have a look at some example of using the Excel VBA InStr Function

Example 1 – Finding the Position from the beginning

In this example, I will use the InStr function to find the position of ‘V’ in ‘Excel VBA’ from the beginning.

The code for this would be:

Sub FindFromBeginning()
Dim Position As Integer
Position = InStr(1, "Excel VBA", "V", vbBinaryCompare)
MsgBox Position
End Sub

When you run this code, it will show a message box with the value 7, which is the position of ‘V’ in the string ‘Excel VBA’.

Example 2 – Finding the Position from the beginning of the Second Word

Suppose, I want to find the position of ‘the’ in the sentence – ‘The quick brown fox jumps over the lazy dog’

However, I want the search to begin with the second word onwards.

In this case, we need to change the [Start] argument to make sure it specifies the position from where the second word starts.

Here is the code that will do this:

Sub FindFromSecondWord()
Dim Position As Integer
Position = InStr(4, "The quick brown fox jumps over the lazy dog", "the", vbBinaryCompare)
MsgBox Position
End Sub

This code will show the message box with the value 32 as we have specified the starting position as 4. Hence it ignores the first ‘The’ and finds the second ‘the’ in the sentence.

If you want to make it more dynamic, you can enhance the code so that it automatically ignore the first word.

Here is the enhanced code that will do this:

Sub FindFromSecondWord()
Dim StartingPosition As Integer
Dim Position As Integer
StartingPosition = InStr(1, "The quick brown fox jumps over the lazy dog", " ", vbBinaryCompare)
Position = InStr(StartingPosition, "The quick brown fox jumps over the lazy dog", "the", vbBinaryCompare)
MsgBox Position
End Sub

This code first finds the position of a space character and stores it in the variable StartingPosition.

It then uses this variable as the starting position to look for the word ‘the’.

Hence it returns 32 (which is the starting position of ‘the’ after the first word).

Example 3 – Finding the Position of @ in Email Address

You can easily create a custom function to find the position of @ in an email address using the Excel VBA InStr function.

Here is the code to create the custom function:

Function FindPosition(Ref As Range) As Integer
Dim Position As Integer
Position = InStr(1, Ref, "@")
FindPosition = Position
End Function

Now you can use this custom function as any other worksheet function. It will take a cell reference as input and give you the position of @ in it.

Excel VBA InStr Function - Finding @

Similarly, you can create a custom function to find the position of any substring within the main string.

Example 4 – Highlighting a Part of String within Cells

This is the query that was asked by June (my reader who also inspired me to write this tutorial).

Here is a sample data in the format June sent me:

Her query was to make the numbers outside the bracket bold.

Here is the code I created that does this:

Sub Bold()
Dim rCell As Range
Dim Char As Integer
For Each rCell In Selection
 CharCount = Len(rCell)
 Char = InStr(1, rCell, "(")
 rCell.Characters(1, Char - 1).Font.Bold = True
Next rCell
End Sub

The above code uses the For Each loop to go through each of the cells in the selection. It identifies the position of the opening bracket character using the InStr function. It then changes the font of the text before the bracket.

To use this code, you need to copy and paste in a module in the VB editor.

Once you have copy pasted the code, select the cells in which you want to do this formatting and run the macro (as shown below).

Excel VBA InStr Function - Bold Format Demo

You May Also Like the following Excel VBA Tutorials:

  • Excel VBA SPLIT Function.
  • VBA TRIM Function.
  • The Ultimate Guide to Excel VBA Loops.
  • A Beginner’s Guide to Using For Next Loop in Excel VBA.
  • How to Create and Use an Excel Add-in.
  • How to Combine Multiple Workbooks into One Excel Workbook.
  • How to Count Colored Cells in Excel.
  • Useful Excel VBA Macro Examples for Beginners.
  • How to Sort Data in Excel using VBA (A Step-by-Step Guide)

totn Excel Functions


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.

На чтение 12 мин. Просмотров 18.2k.

VBA Instr

Функция VBA InStr является одной из наиболее часто используемых функций в VBA. Он используется для нахождения текста внутри строки и действительно отлично справляется с работой.

Тем не менее, она часто используется, чтобы помочь извлечь часть строки, и эту задачу она выполняет плохо.

Если вы обнаружили, что извлечение текста в VBA является болезненным процессом, тогда читайте дальше. Эта статья покажет вам более простой и лучший способ, используя три реальных примера!

Содержание

  1. Краткое руководство к статье
  2. Краткая справка
  3. Введение
  4. Когда VBA InStr, Left, Right и Mid полезны
  5. Работа со строками различной длины
  6. Использование функции VBA InStr с Mid
  7. Функция Split
  8. Пример 1: Получение части имени файла
  9. Пример 2: диапазон IP-адресов
  10. Пример 3. Проверьте правильность имени файла
  11. Заключение

Краткое руководство к статье

В следующей таблице приведено краткое руководство к тому, что рассматривается в этой статье.

Строка Тип Задача Как
1234ABC334 Фиксированный размер Оставить слева 4 символа Left(s,4)
1234ABC334 Фиксированный размер Оставить
справа 3
символа
Right(s,3)
1234ABC334 Фиксированный размер Оставить 5, 6, 7 символы Mid(s,5,3)
«Иван
Петрович
Сидоров»
Переменный
размер
Оставить имя Split(s,» «)(0)
«Иван
Петрович
Сидоров»
Переменный
размер
Оставить
отчество
Split(s,» «)(1)
«Иван
Петрович
Сидоров»
Переменный
размер
Оставить
фамилию
Split(s,» «)(2)
«Иван
Петрович
Сидоров»
Переменный
размер
Оставить
фамилию
Dim v As
Variant
v = Split(s, » «)
lastname= v(UBound(v))

Краткая справка

Чтобы узнать больше об элементах, упомянутых в статье, перейдите по следующим ссылкам:

  • Если вы хотите узнать больше о функциях InStr или InStrRev, пожалуйста, прочитайте Поиск в строке.
  • Если вы хотите узнать больше о функциях Mid, Left или Right, посмотрите раздел Извлечение части строки.
  • Для получения дополнительной информации о функции Split проверьте Строка в массив, используя Split.
  • Оператор Like включен в Сравнение строк с шаблоном

Я использую Debug.Print в моих примерах. Он печатает значения в Immediate Window, которое вы можете просмотреть, нажав Ctrl + G (или выберите View-> Immediate Window)

Введение

В этой статье я собираюсь показать вам лучший способ извлечения символов из строки, чем использование функции VBA InStr с Left, Right или Mid.

Эта статья разбита следующим образом:

  • Раздел 1: Как извлечь из строк фиксированного размера.
  • Раздел 2: Как извлечь из строк переменного размера.
  • Раздел 3: Как извлечь из строки переменного размера, используя функцию Split.
  • Разделы с 4 по 6: некоторые примеры из реальной жизни.

Когда VBA InStr, Left, Right и Mid полезны

Если вы хотите проверить, содержит ли строка значение, InStr подходит для этой работы. Если вы хотите сделать простое извлечение, то отлично подойдут Left, Right и Mid.

Использование InStr для проверки, содержит ли строка текст

В следующем примере мы проверяем, содержит ли ФИО «Петрович». Если возвращаемое значение InStr больше нуля, то строка содержит значение, которое мы проверяем.

' Проверьте, содержит ли строка Петрович
    If InStr("Иван Петрович Сидоров", "Петрович") > 0 Then
        Debug.Print "Найдено"
    End If

Извлечение с Left, Right и Mid

Функция Left используется для получения символов слева от строки.
Функция Right используется для получения символов справа от строки.
Функция Mid используется для середины строки. Она такая же, как
Left, за исключением того, что вы даете ему стартовую позицию.

Sub IzvlechTekst()

    Dim s As String: s = "ABCD-7789.WXYZ"

    Debug.Print Left(s, 2) ' Печатает AB
    Debug.Print Left(s, 4) ' Печатает ABCD

    Debug.Print Right(s, 2) ' Печатает YZ
    Debug.Print Right(s, 4) ' Печатает WXYZ

    Debug.Print Mid(s, 1, 2) ' Печатает AB
    Debug.Print Mid(s, 6, 4) ' Печатает 7789

End Sub

VBA Left, Right and Mid

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

Используйте Left, Right или Mid, когда символы всегда будут в одной и той же позиции.

Работа со строками различной длины

Многие из строк, с которыми вы имеет дело, разной длины. Простой пример — когда у вас есть дело со списком имен. Длина строки и требуемая часть (например, имя) могут каждый раз отличаться. Например:

Brooke Hilt
Pamela Jurado
Zack Kinzel
Eddy Wormley
Kaitlyn Rainer
Jacque Trickett
Kandra Stanbery
Margo Hoppes
Berenice Meier
Garrett Hyre

(Если вам нужен случайный список имен, попробуйте этот генератор случайных имен)

Использование функции VBA InStr с Left

В следующем примере мы собираемся получить имя из строки. В этой строке первое имя — это имя перед первым пробелом.

Мы используем функцию VBA InStr, чтобы получить позицию первого пробела. Мы хотим получить все символы до пробела. Мы вычитаем одну из позиции, так как это дает нам позицию последней буквы имени.

Sub PoluchitImya()

    Dim s As String, lPosition As Long

    s = "John Henry Smith"
    ' Печатает John
    lPosition = InStr(s, " ") - 1
    Debug.Print Left(s, lPosition)

    s = "Lorraine Huggard"
    ' Печатает Lorraine
    lPosition = InStr(s, " ") - 1
    Debug.Print Left(s, lPosition)

End Sub

Давайте посмотрим на первый пример в приведенном выше коде. Первый пробел находится в позиции 5. Мы вычтем 1, что дает нам позицию 4. Это позиция последней буквы John, т.е.

VBA InStr and Left

Затем мы даем 4 функции Left, и она возвращает первые четыре символа, например, «John»

Мы можем выполнить ту же задачу в одной строке, передав возвращаемое значение из InStr в функцию Left.

 Dim s As String
    s = "John Henry Smith"

    ' Печатает John
    Debug.Print Left(s, InStr(s, " ") - 1)

Использование функции VBA InStr с Right

В этом примере мы получим последнее слово в строке, то есть Smith. Мы можем использовать функцию InStrRev. Это то же самое, что InStr, за исключением того, что поиск выполняется с конца строки.

Важно отметить, что InStrRev дает нам позицию с начала строки. Поэтому нам нужно использовать его немного иначе, чем мы использовали InStr и Left.

Sub PoluchitFamiliyu()

    Dim s As String: s = "John,Henry,Smith"
    Dim Position As Long, Length As Long

    Position = InStrRev(s, ",")
    Length = Len(s)

    ' Печатает Smith
    Debug.Print Right(s, Length - Position)

    ' Альтернативный метод. Печатает Smith - делает в одну строку
    Debug.Print Right(s, Len(s) - InStrRev(s, ","))

End Sub

Как работает приведенный выше пример:

  • Мы получаем позицию последнего пробела, используя InStrRev: 11
  • Мы получаем длину строки: 16.
  • Вычитаем позицию из длины: 16-11 = 5
  • Мы даем 5 функции Right и возвращаем Smith

VBA Instr and Right

Использование функции VBA InStr с Mid

В следующем примере мы получим «Henry» из строки. Слово, которое мы ищем, находится между первым и вторым пробелом.

Мы будем использовать функцию Mid здесь.

Sub PoluchitVtoroeImya()

    Dim s As String: s = "John Henry Smith"

    Dim firstChar As Long, secondChar As Long
    Dim count As Long

    ' Найти пробел плюс 1. Результат 6
    firstChar = InStr(s, " ") + 1
    ' Найти 2-й пробел. Результат 11
    secondChar = InStr(firstChar, s, " ")
    ' Получить число символов. Результат 5
    count = secondChar - firstChar

    ' Печатает Henry
    Debug.Print Mid(s, firstChar, count)

End Sub

Как видите, это сложно сделать и требует немного усилий, чтобы выяснить. Нам нужно найти первое место. Тогда нам нужно найти второе место. Затем мы должны вычесть одно из другого, чтобы дать нам количество символов, которые нужно взять.

VBA Instr and Mid

Если у вас есть строка с большим количеством слов, то это может быть очень сложно. К счастью для нас, гораздо проще было извлечь символы из строки. Это называется функцией Split.

Функция Split

Мы можем использовать функцию Split для выполнения приведенных выше примеров. Функция Split разбивает строку на массив. Тогда мы можем легко получить доступ к каждому элементу.

Давайте попробуем те же три примера еще раз, и на этот раз мы будем использовать Split.

  Dim s As String: s = "John Henry Smith"

    Debug.Print Split(s, " ")(0) ' John
    Debug.Print Split(s, " ")(1) ' Henry
    Debug.Print Split(s, " ")(2) ' Smith

Ого! Какая разница с использованием Split. Как это работает:

  1. Функция Split разбивает строку везде, где есть пробел.
  2. Каждый элемент помещается в массив, начиная с нуля.
  3. Используя номер местоположения, мы можем получить доступ к элементу массива.  

В следующей таблице показано, как может выглядеть массив после использования Split.

Примечание: первая позиция в массиве равна нулю. Наличие нулевых массивов является стандартным в языках программирования.

0 1 2
John Henry Smith

В приведенном выше коде мы разделяем строку каждый раз, когда ее используем. Мы также можем разделить строку один раз и сохранить ее в переменной массива. Тогда мы можем получить к нему доступ, когда захотим.

Sub SplitName()
    Dim s As String: s = "John Henry Smith"
    Dim arr() As String
    arr = Split(s, " ")

    Debug.Print arr(0) ' John
    Debug.Print arr(1) ' Henry
    Debug.Print arr(2) ' Smith
End Sub

Если вы хотите узнать больше о массивах, я написал о них целую статью под названием «Полное руководство по использованию массивов в Excel VBA».

В следующих разделах мы рассмотрим примеры из реальной жизни. Вы увидите преимущество использования Split вместо функции InStr.

Пожалуйста, не стесняйтесь попробовать это сами. Это отличный способ учиться, и вы можете повеселиться, пытаясь понять их (или, может быть, только у меня так!)

Пример 1: Получение части имени файла

Представьте, что мы хотим извлечь числа из следующих имен файлов

«VB_23476_Val.xls»
«VV_987_Val.txt»
«VZZA_12223_Val.doc»

Это похоже на пример, где мы получаем второй элемент. Чтобы получить значения здесь, мы используем подчеркивание (то есть «_»), чтобы разбить строку. Смотрите пример кода ниже:

Sub PoluchitNomer()

    ' Печатает 23476
    Debug.Print Split("VB_23476_Val.xls", "_")(1)
    ' Печатает 987
    Debug.Print Split("VV_987_Val.txt", "_")(1)
    ' Печатает 12223
    Debug.Print Split("ABBZA_12223_Val.doc", "_")(1)

End Sub

В реальном мире вы обычно читаете такие строки из разных ячеек. Допустим, эти имена файлов хранятся в ячейках от А1 до А3. Мы немного изменим приведенный выше код:

Sub ChitatNomera()

    Dim c As Range
    For Each c In Range("A1:A3")
        ' Разделите каждый элемент по мере его прочтения
        Debug.Print Split(c, "_")(1)
    Next c

End Sub

Пример 2: диапазон IP-адресов

Пример здесь взят из вопроса на веб-сайте StackOverflow.

У пользователя есть строка с IP-адресом в формате «BE-ABCDDD-DDS 172.16.23.3».

Он хочет, чтобы IP в диапазоне от 172,16 до 172,31 был действительным. Так например:

  • «BE-ABCDDD-DDS 172.16.23.3» действителен
  • «BE-ABCDDD-DDS 172.25.23.3» действителен
  • «BE-ABCDDED-DDS 172.14.23.3» не действителен
  • «BE-ABCDDDZZ-DDS 172.32.23.3» не действителен

Вот как бы я это сделал. Сначала я разбил строку по периодам. Число, которое мы ищем, находится между первым и вторым периодом. Поэтому это второй пункт. Когда мы разделяем строку, она помещается на первую позицию в массиве (помните, что массив начинается с нулевой позиции).

Полученный массив будет выглядеть так:

0 1 2 3
BE-ABCDDD-DDS 172 31 23 3

Код ниже показывает, как это сделать.

Sub IPAdd()

    ' Проверьте номер, чтобы проверить разные IP-адреса
    Dim s1 As String: s1 = "BE-ABCDDD-DDS 172.31.23.3"

    ' Разбить строку, используя символ точки
    Dim num As Long
    num = Split(s1, ".")(1)

    ' Проверьте правильность номера
    Debug.Print num >= 16 And num <= 31

End Sub

Пример 3. Проверьте правильность имени файла

В этом последнем примере мы хотим проверить правильность имени файла. Есть три правила.

  1. Должно заканчиваться на .pdf
  2. Он должен содержать АА
  3. Он должен содержать 1234 после А

В следующих таблицах показаны некоторые допустимые и недействительные элементы:

Имя файла Статус
AA1234.pdf Действителен
AA_ljgslf_1234.pdf Действителен
AA1234.pdf1 Недействительно — не заканчивается на .pdf
1234 AA.pdf Недействительно — АА не до 1234
12_AA_1234_NM.pdf Действителен

Сначала мы сделаем это, используя функции InStr и Right.

Sub IspInstr()

    Dim f As String: f = "AA_1234_(5).pdf"

    ' Сначала найдите АА, так как 1234 должен идти после
    Dim lPos As Long: lPos = InStr(f, "AA")
    ' Ищите 1234 и убедитесь, что последние четыре символа - .pdf
    Debug.Print InStr(lPos, f, "1234") > 0 And Right(f, 4) = ".pdf"

End Sub

Этот код очень грязный. К счастью для нас, у VBA есть Сравнение с шаблоном. Мы можем проверить шаблон строки без необходимости искать элементы и позиции и т.д. Мы используем оператор Like в VBA для сопоставления с шаблоном. Пример ниже показывает, как это сделать.

Sub IspSravnenie()

    Dim f As String: f = "AA_1234_(5).pdf"

    ' Определить шаблон
    Dim pattern As String: pattern = "*AA*1234*.pdf"
    ' Проверьте каждый элемент по шаблону
    Debug.Print f Like pattern   ' ИСТИНА

End Sub

В приведенном выше примере звездочка в шаблоне относится к любому количеству символов.

Давайте разберем этот паттерн * AA * 1234 * .pdf

*- любая группа символов
AA — точные символы AА

*- любая группа символов
1234 — точные символы 1234

*- любая группа символов
.pdf — точные символы .pdf

Чтобы показать, что это работает правильно, давайте попробуем это на всех именах примеров в таблице.

Sub IspSravnenieTest()

    ' Создать коллекцию имен файлов
    Dim coll As New Collection
    coll.Add "AA1234.pdf"
    coll.Add "AA_ljgslf_1234.pdf"
    coll.Add "AA1234.pdf1"
    coll.Add "1234 AA.pdf"
    coll.Add "12_AA_1234_NM.pdf"

    ' Определить шаблон
    Dim pattern As String: pattern = "*AA*1234*.pdf"

    ' Проверьте каждый элемент по шаблону
    Dim f As Variant
    For Each f In coll
        Debug.Print f Like pattern
    Next f

End Sub

На выходе:

ИСТИНА
ИСТИНА
ЛОЖЬ
ЛОЖЬ
ИСТИНА

Чтобы узнать больше о сопоставлении с шаблоном и ключевом слове Like, ознакомьтесь с этой публикацией.

Заключение

InStr и InStrRev действительно полезны только для простых задач, таких как проверка наличия текста в строке.

Left, Right и Mid полезны, когда положение текста всегда одинаково.

Функция Split — лучший способ извлечь переменную строку.

При попытке проверить формат строки, которая не является фиксированной по размеру, ключевое слово Like (т.е. Сопоставление с образцом) обычно обеспечивает более простое решение.

Simple Instr Function | Start Position | Zero | Instr and If | Case-insensitive Search

Use Instr in Excel VBA to find the position of a substring in a string. The Instr function is quite versatile.

Place a command button on your worksheet and add the code lines below. To execute the code lines, click the command button on the sheet.

Simple Instr Function

By default, the Instr function starts searching at the beginning of the string (position 1).

Code:

Dim state As String
state = «Virginia»

MsgBox InStr(state, «gin»)

Result:

Instr Result

Note: string «gin» found at position 4.

Start Position

The second Instr function below starts searching at position 7.

Code:

Dim state As String
state = «South Carolina»

MsgBox InStr(state, «o»)
MsgBox InStr(7, state, «o»)

Result:

Position 2

Position 10

Explanation: the first Instr function finds the string «o» at position 2. The second Instr function starts searching at position 7 and finds the string «o» at position 10.

Zero

The Instr function returns 0 if the string is not found (important as we will see next).

Code:

Dim state As String
state = «Florida»

MsgBox InStr(state, «us»)

Result:

Zero Result

Conclusion: string «us» not found.

Instr and If

Let’s create a simple VBA program that uses the Instr function.

Code:

Dim state As String, substring As String

state = Range(«A2»).Value
substring = Range(«B2»).Value

If InStr(state, substring) > 0 Then
    Range(«C2»).Value = «Found»
Else
    Range(«C2»).Value = «Not Found»
End If

Result when you click the command button on the sheet:

Instr and If

Explanation: string «outh» found at position 2. The Instr function returns 2. As a result, Excel VBA places the string «Found» into cell C2.

Case-insensitive Search

By default, the Instr function performs a case-sensitive search. Enter the string «dakota» into cell B2 and click the command button on the sheet.

Case-sensitive Search

Explanation: string «dakota» not found (first letter not capitalized). The Instr function returns 0. As a result, Excel VBA places the string «Not Found» into cell C2.

To perform a case-insensitive search, update the code as follows:

Dim state As String, substring As String

state = Range(«A2»).Value
substring = Range(«B2»).Value

If InStr(1, state, substring, vbTextCompare) > 0 Then
    Range(«C2»).Value = «Found»
Else
    Range(«C2»).Value = «Not Found»
End If

Result when you click the command button on the sheet:

Case-insensitive Search

Explanation: the Instr function shown above has 4 arguments. To perform a case-insensitive search, always specify a start position (first argument) and use vbTextCompare (fourth argument).

Понравилась статья? Поделить с друзьями:
  • Vba excel позднее связывание
  • Vba excel подчеркнутый текст
  • Vba excel подчеркивание текста
  • Vba excel подсчет уникальных значений
  • Vba excel подсчет символов в строке