Left right vba excel

Извлечение (вырезание) части строки с помощью кода VBA Excel из значения ячейки или переменной. Функции Left, Mid и Right, их синтаксис и аргументы. Пример.

Эта функция извлекает левую часть строки с заданным количеством символов.

Синтаксис функции Left:

Left(строка, длина)

  • строка — обязательный аргумент: строковое выражение, из значения которого вырезается левая часть;
  • длина — обязательный аргумент: числовое выражение, указывающее количество извлекаемых символов.

Если аргумент «длина» равен нулю, возвращается пустая строка. Если аргумент «длина» равен или больше длины строки, возвращается строка полностью.

Функция Mid

Эта функция извлекает часть строки с заданным количеством символов, начиная с указанного символа (по номеру).

Синтаксис функции Mid:

Mid(строка, начало, [длина])

  • строка — обязательный аргумент: строковое выражение, из значения которого вырезается часть строки;
  • начало — обязательный аргумент: числовое выражение, указывающее положение символа в строке, с которого начинается извлекаемая часть;
  • длина — необязательный аргумент: числовое выражение, указывающее количество вырезаемых символов.

Если аргумент «начало» больше, чем количество символов в строке, функция Mid возвращает пустую строку. Если аргумент «длина» опущен или его значение превышает количество символов в строке, начиная с начального, возвращаются все символы от начальной позиции до конца строки.

Функция Right

Эта функция извлекает правую часть строки с заданным количеством символов.

Синтаксис функции Right:

Right(строка, длина)

  • строка — обязательный аргумент: строковое выражение, из значения которого вырезается правая часть;
  • длина — обязательный аргумент: числовое выражение, указывающее количество извлекаемых символов.

Если аргумент «длина» равен нулю, возвращается пустая строка. Если аргумент «длина» равен или больше длины строки, возвращается строка полностью.

Пример

В этом примере будем использовать все три представленные выше функции для извлечения из ФИО его составных частей. Для этого запишем в ячейку «A1» строку «Иванов Сидор Петрович», из которой вырежем отдельные компоненты и запишем их в ячейки «A2:A4».

Sub Primer()

Dim n1 As Long, n2 As Long

Range(«A1») = «Иванов Сидор Петрович»

‘Определяем позицию первого пробела

n1 = InStr(1, Range(«A1»), » «)

‘Определяем позицию второго пробела

n2 = InStr(n1 + 1, Range(«A1»), » «)

‘Извлекаем фамилию

Range(«A2») = Left(Range(«A1»), n1 1)

‘Извлекаем имя

Range(«A3») = Mid(Range(«A1»), n1 + 1, n2 n1 1)

‘Извлекаем отчество

Range(«A4») = Right(Range(«A1»), Len(Range(«A1»)) n2)

End Sub

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

Welcome to this article on the VBA Left, Right and Mid string functions. In this post, I will show you when to use these functions and equally importantly when to avoid using them. If you use them for the wrong type of tasks(i.e. extracting from variable strings), you can waste a considerable amount of time.

I will also cover a little-known feature of the Mid function where you can update the original string using Mid.

Syntax of Left, Right and Mid functions

These three functions all have a very similar purpose and that is to extract text from a text string. You can see the syntax of these functions in this table:

Function Parameters Description Example
Left string, length Return chars from left side Left(«John Smith»,4)
Right string, length Return chars from right side Right(«John Smith»,5)
Mid string, start, length Return chars from middle Mid(«John Smith»,3,2)

Introduction

First of all, what is a string? A string is a piece of text. You can see examples below:

text = "Mary had a little lamb"
text = "John Smith"
text = "Customer 234-AA=56"

We call the variable type String in VBA and it is equivalent to text in a cell on a spreadsheet.

So let’s get started by setting up a simple piece of code so that we can use to show the results of these string functions. First of all, we create the text variable, and then we assign some text to it:

Dim text As string
text = "Mary had a little lamb"

Then we create a variable and this variable will store the result of the Left, Right or Mid function. We start by assigning the text string to the variable without making any changes:

Sub UseLeft()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
    ' set result to have the same text
    result = text
    
    ' View result in the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

Let’s run this code by clicking in the sub and pressing F5(this is the same as selecting Run->Run Sub/UserForm from the menu.)

You can see that both strings were shown in the Immediate window:

(Note: If the Immediate window is not visible then select View->Immediate Window from the menu or Ctrl + G)

So now that we have our basic code in place. Let’s go ahead and use it to show how these functions work.

Left Function

The Left function is possibly the simplest function in VBA. It returns a given number of characters from the left of a string. All you have to do it to tell it the number of characters that you want to get.
Syntax
Left(String, Length)

Example
Left(“abcdef”, 3)

Result
“abc”

The key thing to remember is that the original string is not changed. We get the result of the Left function and we store it in a different string. The original string remains the same.

In the following example, we’re going to return the first four characters of the string, which are Mary:

Sub UseLeft()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
    ' store the result of the Left function in the result variable
    result = Left(text, 4)
    
    ' Print the result to the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

VBA Left

If we change 4 to 8, you will see that the function now returns the first eight characters of the string:

Sub UseLeft()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
    ' store the result of the Left function in the result variable
    result = Left(text, 8)
    
    ' View result in the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

VBA Left

If we use a value greater than the length of the string, then the entire string is returned. For example, in the next example, we use 100 with the Left function and you can see that the entire string has been returned:

Sub UseLeft()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
    ' store the result of the Left function in the result variable
    result = Left(text, 100)
    
    ' View result in the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

VBA Left

That is the Left function and you can see that it is pretty straightforward to use.

Right Function

The Right function is also very straightforward and it is very similar to the Left function. The difference is that it extracts characters from the right side of the string rather than from the left side. Right takes the same parameters as Left. It takes the string to extract from and the number of characters that you wish to extract:

Syntax
Right(String, Length)

Example
Right(“abcdef”, 3)

Result
“def”

Let’s change the code that we were using with Left. We replace the Left function with the Right function and set the length to 4:

Sub UseRight()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
    ' store the result of the Right function in the result variable
    result = Right(text, 4)
    
    ' View result in the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

When we run this code and you can see that it has returned the last four characters of the string:
VBA Right

Let’s try another example, this time we’re changing the length to 11:

Sub UseRight()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
     ' store the result of the Right function in the result variable
    result = Right(text, 11)
    
    ' View result in the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

Let’s run this code, now you can see that it returns the characters little lamb which are the last 11 characters:

VBA Right

Let’s try one more thing. This time we’re changing the length to 100 which is a number greater than the length of the entire string:

Sub UseRight()

    Dim text As String, result As String
    text = "Mary had a little lamb"
    
     ' store the result of the Right function in the result variable
    result = Right(text, 100)
    
    ' View result in the Intermediate Window(Ctrl + G)
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

Let’s run this code, now you can see that it returns the entire string:

That means that anytime we supply a length that is greater than the length of the string, it will return the entire string.

That is how we use the Right function. As you can see it is very similar to the Left function and quite simple to use.

Mid Function

Now we are going to take a look at the Mid function. The Mid function extracts text from the middle of the string, just as the name implies:

Syntax
Mid(String, Start, Length)

Example
Mid(“abcdef”, 2, 3)

Result
“bcd”

The Mid function is very similar to the Left function. The main difference between Mid and Left is that Mid has one extra parameter – Start. The Start parameter is used to specify where the starting position is in the string:

Syntax
Mid(String, Start, Length)

If we set the Start position to 1, then Mid works exactly the same as Left. If we want to extract text from the string, then we set the Start parameter to the position from where we want to start extracting characters.

Let’s look at some examples so that we can understand it better. In the first example, we use 1 as the start position and 4 as the length. This will produce the same result as using the Left function with 4 as the length:

Let’s try some code with Start as 1 and Length as 4:

Sub UseMid()

    Dim text As string
    text = "Mary had a little lamb"
    
    Dim result As string
    result = Mid(text, 1, 4)
    
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

You can see the result is the same as using Left with 3 as the length:

VBA Mid

To extract the word “had”, we set the start position to 6 and the length to 3.

Sub UseMid()

    Dim text As string
    text = "Mary had a little lamb"
    
    Dim result As string
    result = Mid(text, 6, 3)
    
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

When we run the code, you can see what the result is.

VBA Mid

Now we’re going to extract “little” from this string. We set the start position to 12 and the length to 6:

Sub UseMid()

    Dim text As string
    text = "Mary had a little lamb"
    
    Dim result As string
    result = Mid(text, 12, 6)
    
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

When we run the code, you can see the result:

vba mid

Just like in the other two functions, if we use a length value greater than the length of the text remaining, then the entire string is returned after the start position.

In the next example, we use 5 of the start position and we’re going to use 100 as the length which is obviously longer than the length of the string:

Sub UseMid()

    Dim text As String
    text = "Mary had a little lamb"
    
    Dim result As String
    result = Mid(text, 12, 100)
    
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

When you run the code you will see that you got back all the text from the start position:

VBA Mid

One difference with Mid and the other two functions is that we don’t actually need to specify the length. This parameter is actually optional. If we don’t include the length parameter, it will return the rest of the string from the starting position that we provided. If we remove length from the previous example, so instead of having 100, we just don’t have the parameter, you will see that it also returns the rest of the string from the starting position:

Sub UseMid()

    Dim text As String
    text = "Mary had a little lamb"
    
    Dim result As String
    result = Mid(text, 12)
    
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

Updating the Original String with Mid

At the beginning of this article, I mentioned that Mid has a little-known feature and here I’m going to show you what this feature is. We can update the string using Mid. With the LeftRight functions, we just get back what we’ve extracted from the string. We cannot update the original string with these functions.

The following shows an example of what I mean:

The original string is NOT changed

New string = Left(Original String, Length)
New string = Right(Original String, Length)
New string = Mid(Original String, Start, Length)

The original string is changed
Mid(String, Start, Length) = text

Let’s have a look at some examples to explain how this works. Let’s look at a simple example of Mid first. The following code will return “Mary”:

Sub UseMid()

    Dim text As String
    text = "Mary had a little lamb"
    
    Dim result As String
    result = Mid(text, 1, 4)
    
    Debug.Print "Original: " & text
    Debug.Print "Result: " & result

End Sub

vba mid

Now we will take Mid and put it on the left-hand side of the equals sign. Then we assign it to the string “Jack”. When we run the code, “Jack” will replace “Mary” in the original string:

Sub UpdateUsingMid()

    Dim text As String
    text = "Mary had a little lamb"
    
     Mid(text, 1, 4) = "Jack"
    
    Debug.Print "Original: " & text

End Sub

One thing to keep in mind is how the length works. If we use a length the only the number of characters are replaced. So if we use 4 in the following example then only only 4 characters are replaced:

Mid(text, 1, 4) = "Andrew"

The result is: Andr had a little lamb

But if we don’t use any length then all the letters in the string on the right are used as we can see in this example:

Mid(text, 1) = "Andrew"

The result is: Andrewad a little lamb

If you just want to replace “Mary” with “Andrew” then the easiest thing to do is to use the Replace function:

text = Replace(text, "Mary", "Andrew")

The result is: Andrew had a little lamb

Reading through each character in a string

One useful feature of the Mid function is that it allows us to read through each individual character in a string. We can do it like this:

Sub MidLoop()

    Dim text As String
    text = "abcdef"
    
    Dim i As Long, character As String
    For i = 1 To Len(text)
        character = Mid(text, i, 1)
        Debug.Print i & ":  " & character
    Next i
    
End Sub

When we run this code we get the following result:
1: a
2: b
3: c
4: d
5: e
6: f

Reading through each character in reverse

If we want to read the text in the reverse direction we can do it like this:

Sub MidLoopReverse()

    Dim text As String
    text = "abcdef"
    
    Dim i As Long, character As String
    For i = Len(text) To 1 Step -1
        character = Mid(text, i, 1)
        Debug.Print i & ":  " & character
    Next i
    
End Sub

You will get the following when you run the code:
6: f
5: e
4: d
3: c
2: b
1: a

When to Use/Not Use These Functions

We have seen how to use these functions. The next question is when should we use these functions and when should we avoid using them. These functions work best with fixed strings, but they don’t work so well with variable strings.

Fixed Strings

Fixed strings are where each field in a string is always the same size and in the same position.

For example, you might have records where the first characters are the customer id, the next 4 characters are the year, the next two the transaction type and so on e.g.

1234AB2019XX
4567AB2019YY
1245AB2018ZY

When dealing with strings like this Left, Right and Mid are very useful. But for Variable size strings(i.e. typically a CSV style file), they are not suitable.

Variable sized (delimited) Strings

Variable size strings are ones where the fields may be of different sizes. The end of a field is marked by a delimiter like a comma. These types of strings are very common and you will see them in CSV files.

For example, imagine we have a file with a person’s name and their company name:
Jack Smith, United Block Company,36 High Street
Jenny Cathy Walton, Good Plumbers, Paradise Plaza
Helen McDonald, High-quality Software Providers, 16 Main Avenue

You can see that each field can be a different size. We use the delimiter (the comma in this case) to show us where the field ends.

Many people make the mistake of using our 3 functions with the Instr function to extract the data. For example:

Sub ReadVariableStrings()

    ' Create the test string
    Dim text As String
    text = "Jack Smith,United Block Company,36 High Street"
    
    ' Declare the variables
    Dim person As String, company As String
    Dim startPostion As Long, endPosition As Long
    
    ' Get the persons name
    endPosition = InStr(text, ",")
    person = Left(text, endPosition - 1)
    
    ' Get the company name
    startPostion = endPosition + 1
    endPosition = InStr(startPostion, text, ",") - 1
    company = Mid(text, startPostion, endPosition - startPostion + 1)
    
    ' Print the results
    Debug.Print person
    Debug.Print company

End Sub

You can see that the above code is very longwinded. We actually do this much easier using the Split function which I cover in this article. It has plenty of examples of using split with variable strings.

Here is the code above, rewritten to use the Split function:

Sub ReadVariableStringsSplit()

    ' Create the test string
    Dim text As String
    text = "Jack Smith,United Block Company,36 High Street"
    
    ' Declare the array
    Dim arr As Variant
    
    ' Split the string to an array
    arr = Split(text, ",")
   
    ' Print the results
    Debug.Print arr(0) ' Person
    Debug.Print arr(1) ' Company

End Sub

You can see that this code is much simpler.

Conclusion

In this post, we covered using the Left; Right and Mid functions. These are very useful for extracting text from a fixed-size string. We saw that the Mid function has the added feature which allows us to replace text in a string. We also saw that the Mid function can be used to read through the individual characters in a string.

Related Reading

Excel VBA Split Function – A Complete Guide
The Ultimate Guide to VBA String Functions
The Complete Guide to Using Arrays in Excel VBA

Excel VBA String Functions:

Excel VBA String Functions for Finding and Replacing Text, with Examples: LEFT, RIGHT, MID, LEN, REPLACE, InStr & InStrRev Functions

——————————————————-

Contents:

LEFT Function (Worksheet / VBA)

RIGHT Function (Worksheet / VBA)

MID Function (Worksheet / VBA)

LEN Function (Worksheet / VBA)

REPLACE Function (Worksheet)

REPLACE Function (VBA)

InStr & InStrRev Functions (VBA)

——————————————————-

In Excel vba, a String refers to a sequence of contiguous characters within quotation marks viz. «This is a string expression within quotation marks, in vba.» These characters are literally interpreted as characters, in the sense that these represent the characters themselves rather than their numeric values. A String can include letters, numbers, spaces, and punctuation. A string expression can have as its elements — a string of contiguous characters, a function that returns a string, a string variable, a string constant or a string variant. This section does a detailed discussion on using Excel VBA String Functions to manipulate text strings with vba code. Also refer related link: Excel VBA String Functions: SPLIT, JOIN, CONCATENATE.

LEFT Function (Worksheet / VBA)

The Excel LEFT function can be used both as a worksheet function and a VBA function. The LEFT function returns the specified number of characters in a text string, starting from the first or left-most character. Use this function to extract a sub-string from the left part of a text string. Syntax: LEFT(text_string, char_numbers). It is necessary to mention the text_string argument which is the text string from which you want to extract the specified number of characters. The char_numbers argument is optional (when using as a worksheet function), which specifies the number of characters to extract from the text string. The char_numbers value should be equal to or greater than zero; if it is greater than the length of the text string, the LEFT function will return the text string in full; if omitted, it will default to 1. While using as a VBA function, it is necessary to specify both the arguments, and if text_string contains Null, the function also returns Null.

RIGHT Function (Worksheet / VBA)

The Excel RIGHT function can be used both as a worksheet function and a VBA function. The RIGHT function returns the specified number of characters in a text string, starting from the last or right-most character. Use this function to extract a sub-string from the right part of a text string. Syntax: RIGHT(text_string, char_numbers). It is necessary to mention the text_string argument which is the text string from which you want to extract the specified number of characters. The char_numbers argument is optional (when using as a worksheet function), which specifies the number of characters to extract from the text string. The char_numbers value should be equal to or greater than zero; if it is greater than the length of the text string, the RIGHT function will return the text string in full; if omitted, it will default to 1. While using as a VBA function, it is necessary to specify both the arguments, and if text_string contains Null, the function also returns Null.

MID Function (Worksheet / VBA)

The Excel MID function can be used both as a worksheet function and a VBA function. The MID function returns the specified number of characters in a text string, starting from a specified position (ie. starting from a specified character number). Use this function to extract a sub-string from any part of a text string. Syntax: MID(text_string, start_number, char_numbers). The text_string argument is the text string from which you want to extract the specified number of characters. The start_number argument specifies the character number from which to start extracting the sub-string, the first character in a text string being start_number 1 and incrementing towards the right. The char_numbers argument specifies the number of characters to extract from the text string.

If start_number is greater than the length of the text string, an empty string (zero length) is returned; if it is less than the length of the text string but together with char_numbers (ie. start_number PLUS char_numbers) it is greater than the length of the text string, the MID function will return the text string in full from the start_number position to the end of the text string.

Using MID function as a worksheet function, if a negative value is specified for char_numbers, MID will return the #VALUE! error value; if start_number is less than 1, MID will return the #VALUE! error value. All arguments are necessary to be specified when using as a worksheet function.

Using MID function as a VBA function: The char_numbers argument is optional when used as VBA function, and if omitted the function will return the text string in full from the start_number position to the end of the text string. All other arguments are necessary to be specified when using as a vba function. If text_string contains Null, the function also returns Null.

LEN Function (Worksheet / VBA)

The Excel LEN function can be used both as a worksheet function and a VBA function. The worksheet LEN function returns the number of characters in a text string. Use this function to get the length of a text string. Syntax: LEN(text_string). It is necessary to mention the text_string argument which is the text string whose length you want to get in number of characters. Note that spaces also count as characters. The worksheet LENB function returns the number of bytes used to represent the characters in a text string — counts each character as 1 byte except when a DBCS language [viz. Japanese, Chinese (Simplified), Chinese (Traditional), and Korean] is set as the default language wherein a character is counted as 2 bytes. Syntax: LENB(text_string).

While using LEN as a VBA functionSyntax: Len(text_string) or Len(variable_name) — you can use either a text string or a variable name, and the function will return a Long value representing the number of characters contained in the string or the number of bytes required to store a variable. Using the vba Len function for a variable of type variant will treat the variable as a String and return the number of characters contained in it. A text_string or variable containing Null, will also return Null. The vba Len function returns the number of characters in the string where the variable is of subtype String or Variant, and wherein the variable is of subtype numeric the function returns the number of bytes used to store the variable.

Example — Using Left, Right, Mid & Len functions in vba code.

Sub Left_Right_Mid_Len()
‘using vba Left, Right, Mid & Len functions.

Dim str As String, strLeft As String, strRight As String, strMid As String

str = «James Bond»

strLeft = Left(str, 7)

‘returns «James B», which are the first 7 characters (space is counted as a distinct character).

MsgBox strLeft

strLeft = Left(str, 15)

‘returns «James Bond», which are all characters in cell A1, because the number 15 specified in the function exceeds the string length of 10 characters.

MsgBox strLeft

strRight = Right(str, 7)

‘returns «es Bond», which are the last 7 characters (space is counted as a distinct character).

MsgBox strRight

strRight = Right(str, 15)

‘returns «James Bond», which are all characters in cell A1, because the number 15 specified in the function exceeds the string length of 10 characters.

MsgBox strRight

strMid = Mid(str, 2, 6)

‘Returns «ames B». Starts from the second character ie. «a», and then specifies that 6 characters be returned starting from «a».

MsgBox strMid

strMid = Mid(str, 2, 15)

‘Returns «ames Bond». Returns all characters starting from the second character (start_number position) of «a», because the specified characters of 15 plus start number 2 (ie. total of 17) exceed the string length of 10 characters.

MsgBox strMid

strMid = Mid(str, 2)

‘Returns «ames Bond». Returns all characters starting from the second character (start_number position) of «a», because the second argument (char_numbers) is omitted.

MsgBox strMid

strMid = Mid(str, 12, 2)

‘Returns an empty string (zero length), because the start number of 12 exceeds the string length of 10 characters.

MsgBox strMid

‘Returns 10, the string length measured by its number of characters.

MsgBox Len(str)

‘Returns 10, the string length measured by its number of characters.

MsgBox Len(«James Bond»)

End Sub

Example — Using the vba Len function — variable types.

Sub Len_vbaFunc()
‘using vba Len function — variable types

‘—————————

‘returns 3 in both cases — number of characters in the string:

MsgBox Len(«bad»)

MsgBox Len(«245»)

‘returns 10 — number of characters in the string including the space:

MsgBox Len(«James Bond»)

‘—————————

‘a variable of type variant is treated as a string

Dim vVar As Variant

vVar = 245

‘returns 2, indicating variable subtype Integer:

MsgBox VarType(vVar)

‘Returns 3, the number of characters contained in the variable — the Len functions treats the variant variable as a String:

MsgBox Len(vVar)

‘—————————

‘a variable of type string

Dim strVar As String

strVar = «James Bond»

‘returns 8, indicating variable subtype String:

MsgBox VarType(strVar)

‘Returns 10, the number of characters contained in the variable of type String:

MsgBox Len(strVar)

‘—————————

‘a variable of type integer

Dim iVar As Integer

iVar = 245

‘Returns 2, the number of bytes used to store the variable:

MsgBox Len(iVar)

‘a variable of type long

Dim lVar As Long

lVar = 245

‘Returns 4, the number of bytes used to store the variable:

MsgBox Len(lVar)

‘a variable of type single

Dim sVar As Single

sVar = 245.567

‘Returns 4, the number of bytes used to store the variable:

MsgBox Len(sVar)

‘a variable of type double

Dim dVar As Double

dVar = 245.567

‘Returns 8, the number of bytes used to store the variable:

MsgBox Len(dVar)

‘—————————

End Sub

Example — Using LEN and MID Functions, to determine characters appearing at odd number positions in a text string.

Sub Mid_Len_OddNoCharacters()

‘Using LEN and MID Functions, to determine characters appearing at odd number positions in a text string

Sheets(«Sheet1»).Activate

Dim str As String, strOdd, i As Integer

‘assign text string in cell A2 («HELLO») to variable (str)

str = ActiveSheet.Range(«A2»).Value

‘loop though each character — vba Len function determines the length or number of characters in the text string

For i = 1 To Len(str)

‘check odd number position

If i Mod 2 = 1 Then

‘return character at odd number position, and add it to the string variable srtOdd

‘vba Mid function extracts 1 character from str, starting from character number i

strOdd = strOdd & Mid(str, i, 1)

End If

Next

MsgBox strOdd

‘enter the string (variable srtOdd) containing odd positioned characters in cell A3 («HLO»)

Range(«A3»).Value = strOdd

Example — Using LEFT, LEN and MID Functions, to return initials of full name.

Sub Left_Mid_Len_InitialsOfName()
‘Using LEFT, LEN and MID Functions, to return initials of full name.
‘return initials from a text string containing full name comprising of multiple words
‘consider a string containing the first name, middle name(s) & surname, having inbetween spaces — return initials of full name, wherein each initial is followed by a dot and space.

Sheets(«Sheet1»).Activate

Dim strName As String, strInitials As String

Dim i As Integer

‘assign variable strName to the text string — the first name, middle name(s) & surname with inbetween spaces:

‘strName = «   Alec Thomas stone     Hanson    «

strName = ActiveSheet.Range(«A6»).Value

‘loop though each character:

For i = 1 To Len(strName)

‘if first character

If i = 1 Then

‘if the first character is not blank space, it will be an initial:

If Left(strName, i) <> » » Then

‘add dot after first initial

strInitials = Left(strName, 1) & «.»

End If

‘if NOT first character

Else

‘if any character after the first character is preceded by a blank space, it will be an initial:

If Mid(strName, i — 1, 1) = » » And Mid(strName, i, 1) <> » » Then

‘determines if first initial

If Len(strInitials) < 1 Then

‘add dot after first initial

strInitials = Mid(strName, i, 1) & «.»

‘for multiple initials:

Else

‘for multiple initials, add to the previous initial(s):

strInitials = strInitials & » » & Mid(strName, i, 1) & «.»

End If

End If

End If

Next i

‘convert all initials to upper case:

strInitials = UCase(strInitials)

‘returns «A. T. S. H.» and enter the string variable strInitials in cell A7

MsgBox strInitials

Range(«A7»).Value = strInitials

‘returns 11 — 4 letters, 4 dots & 3 blank spaces

MsgBox Len(strInitials)

REPLACE Function (Worksheet)

The worksheet REPLACE function replaces part of a text string with a new text string, based on specified number of characters and starting from a specified position. Syntax: REPLACE(old_text, start_number, number_of_chars, new_text). It is necessary to specify all arguments. The old_text argument is the text string in which you want to replace with new text. The start_number argument is the position of the character in old_text, which you want to replace (ie. position of the first character from which replacement should start). Position is the character number, first character being number 1 & incrementing towards the right. The number_of_chars is the number of characters which will be replaced in the old_text (with new_text). The new_text is the text string which will replace the characters in old_text.

Example — using the Worksheet Replace Function in vba code to delete blank spaces in excess of a specified number, within a string

Function DeleteBlankSpaces(str As String, iSpaces As Integer) As String
‘using the Worksheet Replace Function in vba code to delete blank spaces in excess of a specified number, within a string (str)
‘use this code to reduce multiple spaces within a string to a specified number of spaces (iSpaces)
‘this code can also delete ALL spaces within a string
‘this code can also convert multiple spaces to a single space within a string, similar to the worksheet Trim function, except that using Trim deletes ALL blank spaces before the first (non-space) character also.

Dim n As Integer, counter As Integer

counter = 0

‘start from last character in the string and move to the first

For n = Len(str) To 1 Step -1

‘if character is blank space

If Mid(str, n, 1) = » « Then

‘increment counter by 1

counter = counter + 1

‘if blank space(s) equal to or less than specified number

If counter < iSpaces + 1 Then

‘go to next character ie. next n

GoTo skip

‘if blank space(s) in excess of specified number, then delete

Else

‘using the worksheet Replace function to replace with a zero-length string

str = Application.Replace(str, n, 1, «»)

End If

‘if character is NOT blank space, go to next character ie. next n

Else

‘restore to 0 if non-blank character

counter = 0

End If

skip:

Next n

‘function returns the final string after deleting excess consecutive blank spaces

DeleteBlankSpaces = str

Sub DelBlSp()
‘delete excess consecutive blank spaces within a string (str) ie. in excess of a specified number
‘Note: this code does not ensure uniform no. of blank spaces but ONLY deletes excess blanks

Sheets(«Sheet1»).Activate

Dim strText As String, iSpaces As Integer

‘assign string in cell A10 (» Specify    max spaces    in  text   .») of active sheet to variable (strText)

strText = ActiveSheet.Range(«A10»).Value

‘specify the maximum number of consecutive spaces to retain within the string — this procedure will delete spaces in excess of this specified Number

‘assign this max number to variable iSpaces

iSpaces = 2

‘strText contains 4 blank spaces after «Specify», 4 blank spaces after «spaces» & 3 blank spaces after «text», all of which are reduced to 2 blank spaces

‘enter final string in cell A11 (» Specify  max spaces  in  text  .») of active sheet — call DeleteBlankSpaces function and pass the arguments of string (strText) & specified blank spaces (iSpaces)

ActiveSheet.Range(«A11»).Value = DeleteBlankSpaces(strText, iSpaces)

Example — ensure uniform no. of consecutive blank spaces within string, where existing blank spaces are present

Function UniformBlankSpaces(str As String, iSpaces As Integer) As String
‘ensure uniform no. of consecutive blank spaces within string, where existing blank spaces are present

Dim n As Integer, counter As Integer

‘counter is used to determine the no. of consecutive blank spaces

counter = 0

‘start from last character in the string and move to the first

For n = Len(str) To 1 Step -1

‘if character is blank space

If Mid(str, n, 1) = » » Then

‘increment counter by 1

counter = counter + 1

‘if blank space(s) is less than specified number

If counter < iSpaces Then

‘if first character of the string is a blank space

If n = 1 Then

‘add blank space

str = Left(str, 1) & » » & Right(str, Len(str) — n)

‘if character preceding blank space at n is NOT a blank Space

ElseIf Mid(str, n — 1, 1) <> » » Then

‘add blank space

str = Mid(str, 1, n) & » » & Right(str, Len(str) — n)

‘if character preceding blank space at n is also a blank Space

Else

‘go to next character ie. next n

GoTo skip

End If

‘if blank space(s) in excess of specified number, then delete

ElseIf counter > iSpaces Then

‘using the worksheet Replace function to replace with a zero-length string

str = Application.Replace(str, n, 1, «»)

End If

‘if character is NOT blank space, go to next character ie. next n

Else

‘restore counter to 0 if non-blank character

counter = 0

End If

skip:

Next n

‘function returns the final string with uniform consecutive blank spaces

UniformBlankSpaces = str

Sub UniformBlSp()
‘ensure uniform no. of consecutive blank spaces within string, where existing blank spaces are present
‘Note: this code ensures uniform no. of blank spaces where lead & trailing spaces are also present

Sheets(«Sheet1»).Activate

Dim strText As String, iSpaces As Integer

‘assign string in cell A10 (» Specify    max spaces    in  text   .») of active sheet to variable (strText)

strText = ActiveSheet.Range(«A10»).Value

‘specify the uniform number of consecutive spaces to retain within the string — this procedure will delete/add spaces in excess/short of this specified Number

‘assign this number to variable iSpaces

iSpaces = 2

‘enter final string in cell A12 (»  Specify  max  spaces  in  text  .») — call UniformBlankSpaces function and pass the arguments of string & specified blank spaces

ActiveSheet.Range(«A12»).Value = UniformBlankSpaces(strText, iSpaces)

REPLACE Function (VBA)

The vba Replace Function is used to return a string in which a specified substring is replaced, a specified number of times, with another specified substring. Syntax:  Replace(expression, find, replace, start, count, compare). It is necessary to specify the arguments of expression, find and replace, while the start, count & compare arguments are optional.

The expression argument is the string in which a specific substring is replaced. For a zero-length expression string a zero-length string is returned, and for a Null expression the function will give an error. The find argument specifies the substring which is to be replaced. If find substring is zero-length, then a copy of the expression is returned. The replace argument specifies that ‘another substring’ which replaces (ie. the replacement substring). A replace substring of zero-length has the effect of deleting all occurrences of find from the expression. The start argument specifies the position (ie. character number) in the expression from where you want to start your search for the ‘find’ substring. If omitted, it will default to1 (ie. search will start from first character position). The string returned by the Replace function begins from this start position till the last character of the expression string, after the replacement(s). Specifying a start position which is greater than the length of the expression, will return a zero-length string. The count argument specifies the number of substring replacements you want to do. Omitting to specify this will default to the value -1, which will make all possible replacements. Specifying zero for the count will have the effect of no replacement and will return a copy of the expression. The compare argument specifies the type of comparison to use for evaluating substrings — a numeric value or a constant can be specified herein, as detailed below.

You can specify the following arguments for the compare argument: vbUseCompareOption (value: -1) performs a comparison using the setting of the Option Compare statement. vbBinaryCompare (value: 0) performs a binary comparison — string comparisons based on a binary sort order (in Microsoft Windows, the code page determines the sort order — wherein ANSI 1252 is used for English and many European languages), wherein uppercase characters are always less than lowercase characters -> A < B < U < Z < a < b < u < z < À < Û < à < û. vbTextCompare (value: 1) performs a textual comparison — string comparisons which are not based on a case-sensitive text sort order -> (A=a) < (À = à) < (B=b) < (U=u) < (Û = û) < (Z=z). vbDatabaseCompare (value: 2) performs a comparison based on information in your database (can be used within Microsoft Access only). If you do not specify the compare argument, the comparison is done based on the defined Option Compare statement. Option Compare Statement (viz. Option Compare Binary or Option Compare Text) can be used to set the comparison method — you must specify ‘Option Compare Binary’ or ‘Option Compare Text’ at the module level, before any procedure. If the Option Compare Statement is not specified, the default text comparison method is Binary.

Example — using the vba Replace function.

Sub Replace_vbaFunc()
‘using the vba Replace function

Dim str As String, strFind As String, strReplace As String

‘find all ocurrences of «s» to be replaced:

strFind = «s»

‘set replace string as zero-length:

strReplace = «»

‘—————————

str = «She was selling sea shells!»

‘returns 27:

MsgBox Len(str)

‘returns the string after deleting all occurences of ‘s’ — «She wa elling ea hell!». Note that capital ‘S’ is not replaced.

str = Replace(str, strFind, strReplace)

MsgBox str

‘returns 22:

MsgBox Len(str)

‘—————————

str = «She was selling sea shells!»

‘returns 27:

MsgBox Len(str)

‘returns the string after deleting all occurences of ‘s’ — «he wa elling ea hell!».

‘Note that capital ‘S’ is also replaced because a textual comparison has been done by setting the compare argument value to vbTextCompare (value: 1).

str = Replace(str, strFind, strReplace, , , 1)

MsgBox str

‘returns 21:

MsgBox Len(str)

‘—————————

str = «She was selling sea shells!»

‘returns 27:

MsgBox Len(str)

‘deleting all occurences of ‘s’ from start position 8 — returns » elling ea hell!». Note that the character number 8 is a blank space and this is also returned.

‘the string returned by the Replace function begins from this start position till the last character of the expression string.

str = Replace(str, strFind, strReplace, 8)

MsgBox str

‘returns 16:

MsgBox Len(str)

‘—————————

str = «She was selling sea shells!»

‘returns 27:

MsgBox Len(str)

‘Specifying a start position which is greater than the length of the expression, will return a zero-length string.

str = Replace(str, strFind, strReplace, 28)

‘returns a zero-length string:

MsgBox str

‘returns 0:

MsgBox Len(str)

‘—————————

str = «She was selling sea shells!»

‘returns 27:

MsgBox Len(str)

‘The count argument specifies the number of substring replacements you want to do. Omitting to specify this will default to the value -1, which will make all possible replacements.

‘specifying a start position of 8, and count of 2:

str = Replace(str, strFind, strReplace, 8, 2)

‘returns » elling ea shells!», after deleting ‘s’ twice from start position of 8.

MsgBox str

‘returns 18:

MsgBox Len(str)

‘—————————

End Sub

Example — Manipulate Strings in Excel VBA — Remove Numericals, Delete/Add Blank Spaces, Capitalize letters.

To download Excel file with live code, click here.

Function StringManipulation(str As String) As String

‘String Manipulation using vba & worksheet Replace funcions, Trim / Len / Right / Mid / Chr / Asc / Ucase function.

‘This code manipulates a string text as follows:
‘1. removes numericals from a text string;
‘2. removes leading, trailing & inbetween spaces (leaves single space between words);
‘3. adds space (if not present) after each exclamation, comma, full stop and question mark;
‘4. capitalizes the very first letter of the string and the first letter of a word after each exclamation, full stop and question mark;

Dim iTxtLen As Integer, iStrLen As Integer, n As Integer, i As Integer, ansiCode As Integer

‘—————————

‘REMOVE NUMERICALS

‘The vba Chr function returns a character (string data type) identified to the specified character code.

‘Excel uses ANSI character set for Windows computers. The Windows operating environment uses the ANSI character set, whereas Macintosh uses the Macintosh character set, so that the returned character corresponds to this character set.

‘chr(48) to chr(57) represent numericals 0 to 9 in ANSI/ASCII Character codes

For i = 48 To 57

‘remove all numericals from the text string using vba Replace function

str = Replace(str, Chr(i), «»)

Next i

‘—————————

‘REMOVE LEADING, TRAILING & INBETWEEN SPACES (LEAVE SINGLE SPACE BETWEEN WORDS)

‘use the worksheet TRIM function. Note: the TRIM function removes space character with ANSI code 32, does not remove the nonbreaking space character with ANSI code 160

str = Application.Trim(str)

‘—————————

‘ADD SPACE (IF NOT PRESENT) AFTER EACH EXCLAMATION, COMMA, DOT AND QUESTION MARK:

‘set variable (iTxtLen) value to string length

iTxtLen = Len(str)

‘start from last character in the string and move to the first

For n = iTxtLen To 1 Step -1

‘Chr(32) returns space; Chr(33) returns exclamation; Chr(44) returns comma; Chr(46) returns dot / full stop; Chr(63) returns question mark;

If Mid(str, n, 1) = Chr(33) Or Mid(str, n, 1) = Chr(44) Or Mid(str, n, 1) = Chr(46) Or Mid(str, n, 1) = Chr(63) Then

‘check if space is not present after, except for the last Character

If Mid(str, n + 1, 1) <> Chr(32) And n <> iTxtLen Then

‘using Mid & Right functions to add space — note that current string length is used

str = Mid(str, 1, n) & Chr(32) & Right(str, iTxtLen — n)

‘update string length — increments by 1 after adding a space (character) — this enables correct use of the Right Function in above line

iTxtLen = iTxtLen + 1

End If

End If

Next n

‘—————————

‘DELETE SPACE (IF PRESENT) BEFORE EACH EXCLAMATION, COMMA, DOT & QUESTION MARK:

‘reset variable value to string length:

iTxtLen = Len(str)

‘exclude the first character

For n = iTxtLen To 2 Step -1

‘Chr(32) returns space; Chr(33) returns exclamation; Chr(44) returns comma; Chr(46) returns full stop; Chr(63) returns question mark;

If Mid(str, n, 1) = Chr(33) Or Mid(str, n, 1) = Chr(44) Or Mid(str, n, 1) = Chr(46) Or Mid(str, n, 1) = Chr(63) Then

‘check if space is present before

If Mid(str, n — 1, 1) = Chr(32) Then

‘using the worksheet Replace function to delete a space:

str = Application.Replace(str, n — 1, 1, «»)

‘omit rechecking the same character again- position of n shifts (decreases by 1) due to deleting a space character:

n = n — 1

End If

End If

Next n

‘—————————

‘CAPITALIZE LETTERS:

‘capitalize the very first letter of the string and the first letter of a word after each exclamation, full stop and question mark, while all other letters are lower case

iStrLen = Len(str)

For i = 1 To iStrLen

‘determine the ANSI code of each character in the string: Excel uses ANSI character set for Windows computers. The Windows operating environment uses the ANSI character set, whereas Macintosh uses the Macintosh character set, so that the returned character corresponds to this character set.

‘The vba Asc function returns the corresponding character code (Integer data type) for the string letter — Asc(string).

ansiCode = Asc(Mid(str, i, 1))

Select Case ansiCode

’97 to 122 are the ANSI codes equating to small cap letters «a» to «z»

Case 97 To 122

‘character no 3 onwards to enable determining if 2 positions preceding it is an exclamation, full stop & question mark

If i > 2 Then

‘capitalizes a letter whose position is 2 characters after (1 character after, will be the space character added earlier) an exclamation, full stop & question mark:

If Mid(str, i — 2, 1) = Chr(33) Or Mid(str, i — 2, 1) = Chr(46) Or Mid(str, i — 2, 1) = Chr(63) Then

Mid(str, i, 1) = UCase(Mid(str, i, 1))

End If

‘capitalize first letter of the string:

ElseIf i = 1 Then

Mid(str, i, 1) = UCase(Mid(str, i, 1))

End If

‘if capital letter, skip to next character (ie. next i):

Case Else

GoTo skip

End Select

skip:

Next i

‘—————————

‘function returns the final manipulated string

StringManipulation = str

End Function

Sub Str_Man()
‘manipulate string

Sheets(«Sheet2»).Activate

Dim strText As String

‘specify the text string which is required to be manipulated (» 2manipulate    text string8 ,    by   vba   Code   .check   below cell  !    ok ?thanks 7 .   «), and assign to string variable strText

strText = ActiveSheet.Range(«A2»).Value

‘enter manipulated string in cell A3 («Manipulate text string, by vba Code. Check below cell! Ok? Thanks.») of active sheet — call StringManipulation function and pass the string (str) argument

ActiveSheet.Range(«A3»).Value = StringManipulation(strText)

End Sub

Example — Replace all occurrences of a substring in a string expression, with another substring — using the vba Replace function.

To download Excel file with live code, click here.

Function Replace_Str1(var As Variant, vFind As Variant, vReplace As Variant, iOption As Integer) As Variant

‘Replaces all occurrences of substring (vFind) in the string (var), with another substring (vReplace) — using the vba Replace function.

‘position of the first occurrence of vFind, within var:

iPosn = InStr(var, vFind)

‘if vFind not found within var

If iPosn < 1 Then

‘return var string:

Replace_Str1 = var

‘if vFind found within var

Else

‘use the vba Replace function to replace all instances of vFind with vReplace

Replace_Str1 = Replace(var, vFind, vReplace, , , iOption)

End If

Sub ReplaceStr1()
‘Replaces all occurrences of substring (vFind) in the string (var), with another substring (vReplace) — using the vba Replace function.
‘this procedure calls Replace_Str1 function and passes the four argumentes of string (var) in which a specific substring (vFind) is replaced with another substring (vReplace) and the type of comparison (iOption) to use for evaluating substrings

Sheets(«Sheet3»).Activate

Dim var As Variant, vFind As Variant, vReplace As Variant, iOption As Integer

‘var is the string within which vFind is searched & replaced by vReplace:

‘var = «she Sells sea shellS«

var = ActiveSheet.Range(«A2»).Value

‘vFind is the string to search within var & which will be replaced by vReplace:

vFind = «s«

‘vReplace is the string which replace all instances of vFind within var:

vReplace = «?«

‘———-

‘to delete all spaces, use a zero-length string for vReplace

‘vFind = » «

‘vReplace = «»

‘———-

‘in a case-insensitive comparison, if you specify to replace occurrences of «a» then instances of both «A» & «a» will be replaced.

‘to perform a binary comparison (case-sensitive), use value 0:

‘iOption = 0

‘to perform a text comparison (case-insensitive), use value 1:

iOption = 1

‘Null: where a variable contains no valid data — Null may have been explicitly assigned to a variable, or it could be a result of an operation between expressions containing Null.

‘if var is Null, exit procedure

If IsNull(var) Then

MsgBox «var is Null, exiting procedure»

Exit Sub

‘if var is not Null:

Else

‘if vFind is Null or a zero-length string:

If IsNull(vFind) Or vFind = «» Then

‘return var without any replacements & exit procedure:

MsgBox «Either vFind is Null or a zero-length»

ActiveSheet.Range(«A3») = var

Exit Sub

Else

‘if var or vFind are not Null, and vFind is not zero-length, replace all instances of vFind («?he ?ell? ?ea ?hell?»):

ActiveSheet.Range(«A3») = Replace_Str1(var, vFind, vReplace, iOption)

End If

End If

InStr & InStrRev Functions (VBA)

The InStr Function returns the position (character number) in which a string first occurs within another string. Syntax: InStr(start, string, substring, compare). It is necessary to specify the arguments of string and substring, while the start & compare arguments are optional.

The start argument specifies the position (ie. character number) within string from where you want to start your search for the substring. It is necessary to specify the start argument, if the compare argument is to be specified. If omitted, it will default to1 (ie. search will start from the first character position). Specifying a start position which is greater than the length of string will return a 0 (zero), and if start contains Null an error will occur. The string argument is the string expression within which substring is being searched. The function returns 0 if string is zero-length, and returns Null if string is Null. The substring argument is the string expression which is being searched within string and whose position will be returned by the function. The function returns 0 if substring is not found, returns the start value if string is zero-length, and returns Null if substring is Null. The compare argument specifies the type of comparison to use for evaluating strings — a numeric value or a constant can be specified herein, as detailed below.

You can specify the following arguments for the compare argument: vbUseCompareOption (value: -1) performs a comparison using the setting of the Option Compare statement. vbBinaryCompare (value: 0) performs a binary comparison — string comparisons based on a binary sort order (in Microsoft Windows, the code page determines the sort order — wherein ANSI 1252 is used for English and many European languages), wherein uppercase characters are always less than lowercase characters -> A < B < U < Z < a < b < u < z < À < Û < à < û. vbTextCompare (value: 1) performs a textual comparison — string comparisons which are not based on a case-sensitive text sort order -> (A=a) < (À = à) < (B=b) < (U=u) < (Û = û) < (Z=z). vbDatabaseCompare (value: 2) performs a comparison based on information in your database (can be used within Microsoft Access only). If you do not specify the compare argument, the comparison is done based on the defined Option Compare statement. Option Compare Statement (viz. Option Compare Binary or Option Compare Text) can be used to set the comparison method — you must specify ‘Option Compare Binary’ or ‘Option Compare Text’ at the module level, before any procedure. If the Option Compare Statement is not specified, the default text comparison method is Binary.

The InStrRev Function returns the position (character number) in which a string first occurs within another string, starting from the end of that another string. Syntax: InStrRev(string, substring, start, compare). Use InStrRev function instead of InStr to search in the reverse direction. It is necessary to specify the arguments of string and substring, while the start & compare arguments are optional. If start is omitted, -1 is used, meaning that the search will begin from the last character position. All other syntax explanations remain same as in the InStr function.

Example — Using the InStr function.

Sub InStrFunc()
‘using the InStr function

Dim str1 As String, str2 As String

‘——————

str1 = «she sells sea shells»

str2 = «e»

‘returns 3:

MsgBox InStr(str1, str2)

‘——————

str1 = «she sells sea shells»

str2 = «e»

‘returns 6:

MsgBox InStr(4, str1, str2)

‘——————

str1 = «she sells sea shells»

str2 = «e»

‘returns 0 because start value (24) is greater than length of str1 (20):

MsgBox InStr(24, str1, str2)

‘——————

str1 = «»

str2 = «e»

‘returns 0 because str1 is zero-length:

MsgBox InStr(str1, str2)

‘——————

str1 = «she sells sea shells»

str2 = «f»

‘returns 0 because str2 is not found:

MsgBox InStr(str1, str2)

‘——————

Dim str3 As Variant

str1 = «she sells sea shells»

str3 = Null

‘returns 1, indicating subtype Null — because str3 is Null:

MsgBox VarType(InStr(str1, str3))

‘——————

str1 = «she Sells sea shells»

str2 = «s»

‘returns 9 — the default text comparison type is Binary (case-sensitive):

MsgBox InStr(2, str1, str2)

‘returns 5 — performing a textual comparison wherein comparison type is not case-sensitive:

MsgBox InStr(2, str1, str2, 1)

‘——————

End Sub

Example — Replace all occurrences of a substring in a string expression, with another substring — using the InStr, Left & Mid functions.

To download Excel file with live code, click here.

Function Replace_Str2(var As Variant, vFind As Variant, vReplace As Variant) As Variant
‘Replace all occurrences of a substring in a string expression, with another substring — using the InStr, Left & Mid functions.
‘Replaces all occurrences of vFind in var, with vReplace — using the InStr, Left & Mid functions.
‘Replacement will be case-sensitive in this procedure ie. if you specify to replace occurrences of «a» then instances of «A» will NOT be replaced.

Dim iPosn As Integer

‘position of the first occurrence of vFind, within var:

iPosn = InStr(var, vFind)

‘length of vFind, which will be replaced with vReplace:

iFindLen = Len(vFind)

‘length of vReplace, which will replaced vFind:

iReplaceLen = Len(vReplace)

‘if vFind not found within var:

If iPosn < 1 Then

‘return var string & exit procedure:

Replace_Str2 = var

Exit Function

‘if vFind found within var:

Else

‘loop:

Do

‘replace vFind with vReplace within var — use the Left & Mid functions to return string. Omitting character nos from the Mid function will return the text string in full from start number position to end of the text string.

var = Left(var, iPosn — 1) & vReplace & Mid(var, iPosn + iFindLen)

‘position of the first occurrence of vFind within updated var, starting the position search from the first character AFTER the latest replacement (iPosn + iReplaceLen)

iPosn = InStr(iPosn + iReplaceLen, var, vFind)

‘if vFind not found within updated var, exit loop

If iPosn = 0 Then Exit Do

Loop

End If

Replace_Str2 = var

Sub ReplaceStr2()
‘Replaces all occurrences of vFind in var, with vReplace — using the InStr, Left & Mid functions.
‘Replacement will be case-sensitive in this procedure ie. if you specify to replace occurrences of «a» then instances of «A» will NOT be replaced.

Sheets(«Sheet3»).Activate

Dim var As Variant, vFind As Variant, vReplace As Variant

‘var is the string within which vFind is searched & replaced by vReplace:

‘var = «she Sells sea shellS«

var = ActiveSheet.Range(«A6»).Value

‘vFind is the string to search within var & which will be replaced by vReplace

vFind = «s«

‘vReplace is the string which replace all instances of vFind within var:

vReplace = «?«

‘if var is Null, exit procedure:

If IsNull(var) Then

MsgBox «var is Null, exiting procedure»

Exit Sub

‘if var is not Null:

Else

‘if vFind is Null or a zero-length string:

If IsNull(vFind) Or vFind = «» Then

‘return var without any replacements & exit procedure

MsgBox «Either vFind is Null or a zero-length»

ActiveSheet.Range(«A7»).Value = var

Exit Sub

Else

‘if var or vFind are not Null, and vFind is not zero-length, replace all instances of vFind («?he Sell? ?ea ?hellS»)

ActiveSheet.Range(«A7»).Value = Replace_Str2(var, vFind, vReplace)

End If

End If

На чтение 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 (т.е. Сопоставление с образцом) обычно обеспечивает более простое решение.

02 Oct Working with Strings in Excel VBA

Posted at 02:54h
in Excel VBA
0 Comments

Howdee! If you’ve ever written any VBA code, you’ve likely had to edit strings in Excel VBA. It can be challenging and more than a little frustrating, especially if you’re not familiar with the tools available to you within the framework. Have you ever had to transform a string of last name comma first name to a traditional full name field in code? Ever had to pull a piece of information out of a string of dozens of characters? Then this article is for you. With that done, let’s dive right in!

VBA InStr & InStrRev Functions

These two functions are, in my opinion, the most crucial text functions to understand when it comes to getting data from inside a string of text in Excel. Once you understand these, you can begin to combine them with other functions to write truly powerful text parsing code.

The Instr function returns the starting position, as a number, of a string within a string of text. For example, we could search the string “I owe you 25 dollars on September 25th” for the literal string “25”. Depending on which function you use you would get different results! Let’s examine the below code:

Sub Instr_InstrRev_Example()
Dim stringExample As String

stringExample = "I owe you 25 dollars on September 25th"

MsgBox InStr(1, stringExample, "25") 'returns 11

MsgBox InStrRev(stringExample, "25") 'returns 35

End Sub

The first message box will display “11” and the second will display “35”. This is important to think about when writing your code, if you need the first or last occurrence of a string within a string, then these functions will serve you very well. In the interest of being thorough, here is the syntax for both functions:

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

Start is an optional parameter that tells the function which character to begin searching. If you omit it, the compiler will start at the first character. String represents the string you’re searching while substring is the string you’re searching for. The compare parameter is also optional and I’ve rarely had need to use it so I won’t confuse you with it now but you’ll almost always use text compare.

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

StringCheck is the string you’re searching while StringMatch is the string you’re searching for. The start variable is optional as it was in InStr. The difference is it starts at the end of the string if omitted. Compare is the same as from the previous function also.

You might be asking yourself what use the VBA Instr and InstrRev functions are if they only return the starting position of a first or last occurrence of a substring. Once we introduce the next function, it will begin to make more sense.

VBA Mid Function

The Mid VBA function extracts a substring from a string based on a starting position and length that you specify. Before diving into examples, let’s look at the syntax:

Mid(text, start_position, number_of_characters)

Text is the full string of text from which you want to remove a substring. Start_position is an integer that represents the starting position of the first character of the string you wish to remove. Finally, number_of_characters is an integer representing the number of characters you wish to return.

Continuing with the sentence we used in the prior example, let’s examine the following code:

Sub MidExample()
Dim stringExample As String

stringExample = "I owe you 25 dollars on September 25th"

MsgBox Mid(stringExample, 1, 5)

End Sub

In this example, our Mid VBA function would return the string “I owe”. That’s because we have told the function to start at the first character in the string and return 5 characters from that point, including the starting character. Combining this function with the two InStr functions from the prior example, you can dynamically tell your Mid function where to start returning text from within a string. Using these functions together is how I primarily handle working with strings in Excel VBA.

VBA Left & Right Functions

If you’ve been using Excel for any period of time, you’ve probably either seen or used the Left and Right worksheet functions. Both of these functions exist in VBA and the syntax is the exact same. So, if you’re familiar with these functions, you can probably skip ahead to the next section but, in the interest of thoroughness, I want to cover these functions for folks who may not have used them before.

By their names, you can probably infer what these two functions do. The Left function returns a specific number of characters from the beginning of a string, while the Right function returns a specified number of characters form the end of a string. The syntax for them looks like this:

Left(text, number_of_characters)

Right(text, number_of_characters)

In both functions, the text input is the string you’re wanting to return a portion of, while the number_of_characters input is an integer representing the number of characters you wish to return. Let’s use our $25 sentence to examine the results in the following code:

Sub LeftRightExample()
Dim stringExample As String

stringExample = "I owe you 25 dollars on September 25th"

MsgBox Left(stringExample, 5)
MsgBox Right(stringExample, 5)

End Sub

In this example, the left function would return “I owe” while the Right example would return “ 25th”. The VBA functions Left & Right are very useful when you need to return the beginning X number of characters or the ending X number of characters from a string. It can also be used to return the beginning/ending portions of substrings when other functions are nested inside the text input. While I use these less than the previous two, they’re incredibly useful when just grabbing the beginning or ends of strings in Excel VBA.

VBA Replace Function

The last function I want to cover in depth is the VBA Replace function. As you might expect from its name, the Replace function replaces a sequence of characters with another sequence of characters. This can be useful when you’re preparing data and need to remove invalid characters from a string, performing what if analysis and need to alter a string based on inputs, etc. Let’s take our sentence we’ve been using and assume we need to change the 25th due date to the 30th. First, let’s examine the syntax to figure out how to do that.

Replace(string1, find, replacement, [start], [count], [compare])

String1 represents the string you want search. For us, this is our entire sentence. Find represents the string we are searching string1 for to perform the replace. The last required field, replacement, is the sequence of characters you want to replace string1 with. Start, an optional parameter, tells the search where to start. If you omit this, it starts at the beginning of the string. Count determines the number of replacements to make. If you leave this blank, it will perform the replace for every occurrence of find. Lastly, compare determines how to compare the strings. As before, you’ll almost always leave this to it’s default of text compare. The code for our example looks like this:

Sub ReplaceExample()
Dim stringExample As String

stringExample = "I owe you 25 dollars on September 25th"

MsgBox Replace(stringExample, "25th", "30th")

End Sub

Other Useful Functions to Edit Strings in Excel VBA

Len(text)

The Len VBA function accepts a string input and returns the number of characters in that string.

UCase(text) & LCase(text)

Both of these functions accept a string input and the UCase function will return the string converted to all upper-case characters while the LCase function returns the string with all characters converted to lower-case. This is very useful when doing string comparisons in VBA.

Str(number)

Str is a useful function that will accept a number from your code and return it as a string so you can then use string and text VBA functions on the number.

Split(expression, [delimiter], [limit], [compare])

Split is a very useful function that will split out substrings based on a delimiter. Expression is the text input. The optional parameter delimiter will default to a space delimiter but you can assign a comma, semi-colon, etc. Limit is also optional and determine the number of strings to split out. This will default to all strings if left blank. Compare, as with other formulas can be almost always be omitted from your function.

Real World Examples

The above functions, while good for explanation purposes, don’t always tell the full story since they aren’t real world examples of how to use these functions. I thought I would toss out a couple of examples of how to use VBA text functions to manipulate strings in Excel VBA with a couple of problems I’ve run into over the years.

The most common issue I run into with data sets, is that there is no universally accepted way to export full names. Almost every database stores names as first and last name fields. The issue is that many systems concatenate these fields together on export but may do it differently. For example, your time tracking system might export names in the format “FirstName LastName” while your payroll system exports names in the format “LastName, FirstName”. If you’re trying to match these names up on a weekly basis for payroll, this can get annoying quickly. Writing a macro to transform one or the other can save you a lot of time over the course of the year.

Sub LastNameFirstNameExample()
Dim lastrow As Long, i As Long
Dim sht As Worksheet
Dim str As String

Set sht = Worksheets("Name Transform Example")
lastrow = sht.UsedRange.Rows.Count

For i = 2 To lastrow
    str = Cells(i, 1)
    Cells(i, 2) = Mid(str, InStr(1, str, ",") + 2, Len(str) - InStr(1, str, ",") + 2) & " " & _
        Left(str, InStr(1, str, ",") - 1)
Next i

End Sub

working with strings in excel vba

This subroutine is an example of how to turn the “LastName, FirstName” format into the “FirstName LastName” format, as seen in the gif above. First, we define the range we want to perform the conversion on and loop through those cells. While looping, we use a combination of the Mid, InStr, Len, and Left functions to reorder the names. Since all names are separate by a comma, it becomes very easy to find the splitting point between the last name and first name and, by using the Len & InStr functions, we can determine exactly how many characters we need to return. Alternatively, we could have used the Split function like this:

Sub LastNameFirstNameExampleTwo()
Dim lastrow As Long, i As Long
Dim sht As Worksheet
Dim str As String
Dim nameArray() As String

Set sht = Worksheets("Name Transform Example")
lastrow = sht.UsedRange.Rows.Count

For i = 2 To lastrow
    str = Cells(i, 1)
    nameArray = Split(str, ",")
    Cells(i, 2) = LTrim(nameArray(1) & " " & nameArray(0))
Next i

End Sub

The nuts and bolts of this are the same, but this example uses a string array and the Split function inside the loop. You can easily split a string of delimited text into a string array and then reorder it. It’s important to remember that it will return all of the string around the split so we need to use the LTrim function in this case to remove the leading space at the beginning of our end result. Both examples are fine but I prefer the split and array example as it is a bit easier to read.

I hope you enjoyed this brief introduction to working with strings in Excel VBA. As always, the example code is available for download for all subscribers. It’s quick and easy to sign up and I won’t ever spam you with unwanted ads and emails. Let me know in the comments if you have any questions on the above.

Cheers,

R

В этой статье разберем работу со строками в VBA на примерах функций InStr, LCASE, UCase, Left, Right, Mid, LTrim, RTrim, Trim, Len, Replace, Space, StrComp, String, StrReverse.

Строки — это последовательность символов, которая может состоять либо из алфавитов, цифр, специальных символов, либо из всех них. Переменная называется строкой, если она заключена в двойные кавычки «».

Содержание:

  • Синтаксис
  • Примеры
  • Строковые функции
  • Название функции и описание
  • InStr
  • Синтаксис
  • Параметр Описание
  • пример
  • Синтаксис
  • Параметр Описание
  • пример
  • LCASE
  • Синтаксис
  • пример
  • UCase
  • Синтаксис
  • пример
  • Left
  • Синтаксис
  • Параметр Описание
  • пример
  • Right
  • Синтаксис
  • Параметр Описание
  • пример
  • Mid
  • Синтаксис
  • Параметр Описание
  • LTrim
  • Синтаксис
  • пример
  • RTrim
  • Синтаксис
  • пример
  • Trim
  • Синтаксис
  • пример
  • Len
  • Синтаксис
  • пример
  • Replace
  • Синтаксис
  • Параметр Описание
  • пример
  • Space
  • Синтаксис
  • Параметр Описание
  • пример
  • StrComp
  • Синтаксис
  • Параметр Описание
  • пример
  • String
  • Синтаксис
  • Параметр Описание
  • пример
  • StrReverse
  • Синтаксис
  • пример

Синтаксис

variablename = "string"

Примеры

str1 = "string"   ' Only Alphabets
str2 = "132.45"   ' Only Numbers
str3 = "!@#$;*"  ' Only Special Characters
Str4 = "Asc23@#"  ' Has all the above

Строковые функции

Существуют предопределенные функции VBA String, которые помогают разработчикам эффективно работать со строками. Ниже приведены методы String, поддерживаемые в VBA. Пожалуйста, нажмите на каждый из методов, чтобы знать подробно.

Название функции и описание

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

Синтаксис

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

Параметр Описание

  • Пуск — необязательный параметр. Указывает начальную позицию для поиска. Поиск начинается с первой позиции слева направо.
  • String1 — требуемый параметр. Строка для поиска.
  • String2 — требуемый параметр. Строка, по которой выполняется поиск String1.
  • Compare — Необязательный параметр. Указывает сравнение строк.Он может принимать следующие значения.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение (по умолчанию)
  • 1 = vbTextCompare — выполняет сравнение текста

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click() 
   Dim Var As Variant 
   Var = "Microsoft VBScript" 
   MsgBox ("Line 1 : " & InStr(1, Var, "s")) 
   MsgBox ("Line 2 : " & InStr(7, Var, "s")) 
   MsgBox ("Line 3 : " & InStr(1, Var, "f", 1)) 
   MsgBox ("Line 4 : " & InStr(1, Var, "t", 0)) 
   MsgBox ("Line 5 : " & InStr(1, Var, "i")) 
   MsgBox ("Line 6 : " & InStr(7, Var, "i")) 
   MsgBox ("Line 7 : " & InStr(Var, "VB")) 
End Sub 

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : 6
Line 2 : 0
Line 3 : 8
Line 4 : 9
Line 5 : 2
Line 6 : 16
Line 7 : 11

Возвращает первое вхождение указанной подстроки. Поиск происходит слева направо.

InStrRev

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

Синтаксис

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

Параметр Описание

  • String1 — требуемый параметр. Строка для поиска.
  • String2 — требуемый параметр. Строка, по которой выполняется поиск String1.
  • Пуск — необязательный параметр. Указывает начальную позицию для поиска. Поиск начинается с первой позиции справа налево.
  • Compare — Необязательный параметр. Указывает сравнение строк.Он может принимать следующие значения.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение (по умолчанию)
  • 1 = vbTextCompare — выполняет сравнение текста

пример

Добавьте кнопку и установите следующую функцию.

Private Sub Constant_demo_Click()
   var = "Microsoft VBScript"
   msgbox("Line 1 : " & InStrRev(var,"s",10))
   msgbox("Line 2 : " & InStrRev(var,"s",7))
   msgbox("Line 3 : " & InStrRev(var,"f",-1,1))
   msgbox("Line 4 : " & InStrRev(var,"t",5))
   msgbox("Line 5 : " & InStrRev(var,"i",7))
   msgbox("Line 6 : " & InStrRev(var,"i",7))
   msgbox("Line 7 : " & InStrRev(var,"VB",1))
End Sub

После выполнения вышеуказанного скрипта он производит следующий результат.

Line 1 : 6
Line 2 : 6
Line 3 : 8
Line 4 : 0
Line 5 : 2
Line 6 : 2
Line 7 : 0

Возвращает первое вхождение указанной подстроки. Поиск происходит справа налево.

LCASE

Функция LCase возвращает строку после преобразования введенной строки в строчные буквы.

Синтаксис

Lcase(String)

пример

Добавьте кнопку и поместите следующую функцию внутри нее.

Private Sub Constant_demo_Click()
   var = "Microsoft VBScript"
   msgbox("Line 1 : " & LCase(var))
   
   var = "MS VBSCRIPT"
   msgbox("Line 2 : " & LCase(var))
   
   var = "microsoft"
   msgbox("Line 3 : " & LCase(var))
End Sub

После выполнения вышеуказанного скрипта он производит следующий вывод.

Line 1 : microsoft vbscript
Line 2 : ms vbscript
Line 3 : microsoft

Возвращает нижний регистр указанной строки.

UCase

Функция UCase возвращает строку после преобразования введенной строки в буквы буквы UPPER.

Синтаксис

UCase(String)

пример

Добавьте кнопку и поместите следующую функцию внутри нее.

Private Sub Constant_demo_Click()
   var = "Microsoft VBScript"
   msgbox("Line 1 : " & UCase(var))
   
   var = "MS VBSCRIPT"
   msgbox("Line 2 : " & UCase(var))
   
   var = "microsoft"
   msgbox("Line 3 : " & UCase(var))
End Sub

После выполнения вышеуказанного скрипта он производит следующий вывод.

Line 1 : MICROSOFT VBSCRIPT
Line 2 : MS VBSCRIPT
Line 3 : MICROSOFT

Возвращает верхний регистр указанной строки.

Left

Функция Left возвращает указанное количество символов с левой стороны данной входной строки.

Синтаксис

Left(String, Length)

Параметр Описание

  • String — обязательный параметр. Строка ввода, из которой указанное число символов должно быть возвращено с левой стороны.
  • Длина — требуемый параметр. Целое число, определяющее количество возвращаемых символов.

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim var as Variant
   
   var = "Microsoft VBScript"
   msgbox("Line 1 : " & Left(var,2))
   
   var = "MS VBSCRIPT"
   msgbox("Line 2 : " & Left(var,5))
   
   var = "microsoft"
   msgbox("Line 3 : " & Left(var,9))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : Mi
Line 2 : MS VB
Line 3 : microsoft

Возвращает определенное количество символов с левой стороны строки.

Right

Функция Right возвращает указанное количество символов с правой стороны данной входной строки.

Синтаксис

Right(String, Length)

Параметр Описание

  • String — обязательный параметр. Строка ввода, из которой указанное число символов должно быть возвращено с правой стороны.
  • Длина — требуемый параметр. Целое число, которое задает количество возвращаемых символов.

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   var = "Microsoft VBScript"
   msgbox("Line 1 : " & Right(var,2))
   
   var = "MS VBSCRIPT"
   msgbox("Line 2 : " & Right(var,5))
   
   var = "microsoft"
   msgbox("Line 3 : " & Right(var,9))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : pt
Line 2 : CRIPT
Line 3 : microsoft

Возвращает определенное количество символов с правой стороны строки.

Mid

Mid функция возвращает указанное количество символов из заданной входной строки.

Синтаксис

Mid(String,start[,Length])

Параметр Описание

  • String — обязательный параметр. Строка ввода, из которой задано количество символов, которые нужно вернуть.
  • Начало — требуемый параметр. Целое число, определяющее начальную позицию строки.
  • Длина — необязательный параметр. Целое число, определяющее количество возвращаемых символов.

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim var as Variant
   var = "Microsoft VBScript"
   msgbox("Line 1 : " & Mid(var,2))
   msgbox("Line 2 : " & Mid(var,2,5))
   msgbox("Line 3 : " & Mid(var,5,7))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : icrosoft VBScript
Line 2 : icros
Line 3 : osoft V

Возвращает определенное количество символов из строки на основе указанных параметров.

LTrim

Функция Ltrim удаляет пробелы с левой стороны строки.

Синтаксис

LTrim(String)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim var as Variant
   var =       "             Microsoft VBScript"
   msgbox "After Ltrim : " & LTrim(var)
End Sub

Когда вы выполняете функцию, она производит следующий вывод.

After Ltrim : Microsoft VBScript

Возвращает строку после удаления пробелов в левой части указанной строки.

RTrim

Функция Rtrim удаляет пробелы с правой стороны строки.

Синтаксис

RTrim(String)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim var as Variant
   var =       "Microsoft VBScript           "
   msgbox("After Rtrim : " & RTrim(var))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

After Rtrim : Microsoft VBScript

Возвращает строку после удаления пробелов в правой части указанной строки.

Trim

Функция Trim удаляет как ведущее, так и конечное пустое пространство данной входной строки.

Синтаксис

Trim(String)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   var = "Microsoft VBScript"
   var =       "            Microsoft VBScript           "
   msgbox ("After Trim : " & Trim(var))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

After trim : Microsoft VBScript

Возвращает строковое значение после удаления как верхнего, так и конечного пробелов.

Len

Функция Len возвращает длину данной входной строки, включая пробелы.

Синтаксис

Len(String)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim var1 as Variant
   Dim var2 as Variant
   
   var1 ="Microsoft VBScript"
   msgbox("Length of var1 is : " & Len(var1))
  
   var2 =       "       Microsoft VBScript           "
   msgbox ("Length of var2 is : " & Len(var2))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Length of var1 is : 18
Length of var2 is : 36

Возвращает длину данной строки.

Replace

Функция Replace заменяет указанную часть строки на определенную строку, указанное количество раз.

Синтаксис

Replace(string,find,replacewith[,start[,count[,compare]]])

Параметр Описание

  • String — обязательный параметр. Строка ввода, которую нужно искать для замены.
  • Find — требуемый параметр. Часть строки, которая будет заменена.
  • Replacewith — обязательный параметр. Строка замены, которая будет заменена на параметр find.
  • Start — необязательный параметр. Задает начальную позицию, из которой нужно искать и заменять строку. Значение по умолчанию — 1.
  • Count — необязательный параметр. Указывает количество раз, которое должна выполняться замена.
  • Compare — Необязательный параметр. Указывает метод сравнения, который будет использоваться. Значение по умолчанию — 0.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение
  • 1 = vbTextCompare — выполняет текстовое сравнение

пример

Private Sub Constant_demo_Click()
   Dim var as Variant
   var = "This is VBScript Programming"
  
   'VBScript to be replaced by MS VBScript
   msgbox("Line 1: " & Replace(var,"VBScript","MS VBScript"))
  
   'VB to be replaced by vb
   msgbox("Line 2: " & Replace(var,"VB","vb"))
  
   ''is' replaced by ##
   msgbox("Line 3: " & Replace(var,"is","##"))
  
   ''is' replaced by ## ignores the characters before the first occurence
   msgbox("Line 4: " & Replace(var,"is","##",5))
  
   ''s' is replaced by ## for the next 2 occurences.
   msgbox("Line 5: " & Replace(var,"s","##",1,2))
  
   ''r' is replaced by ## for all occurences textual comparison.
   msgbox("Line 6: " & Replace(var,"r","##",1,-1,1))
  
   ''t' is replaced by ## for all occurences Binary comparison
   msgbox("Line 7: " & Replace(var,"t","##",1,-1,0))
  
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1: This is MS VBScript Programming
Line 2: This is vbScript Programming
Line 3: Th## ## VBScript Programming
Line 4: ## VBScript Programming
Line 5: Thi## i## VBScript Programming
Line 6: This is VBSc##ipt P##og##amming
Line 7: This is VBScrip## Programming

Возвращает строку после замены строки другой строкой.

Space

Функция Space заполняет строку конкретным количеством пробелов.

Синтаксис

space(number)

Параметр Описание

Номер — требуемый параметр. Количество пробелов, которые мы хотим добавить к данной строке.

пример

Private Sub Constant_demo_Click()
   Dim var1 as Variant
   
   var1 = "Microsoft"
   Dim var2 as Variant
   
   var2 = "VBScript"
   msgbox(var1 & Space(2)& var2)
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Microsoft VBScript

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

StrComp

Функция StrComp возвращает целочисленное значение после сравнения двух заданных строк. Он может возвращать любое из трех значений -1, 0 или 1 на основе входных строк для сравнения.

  • Если String1 меньше String2, то StrComp возвращает -1
  • Если String1 равно String2, то StrComp возвращает 0
  • Если String1 больше String2, то StrComp возвращает 1

Синтаксис

StrComp(string1,string2[,compare])

Параметр Описание

  • String1 — требуемый параметр. Первое строковое выражение.
  • String2 — требуемый параметр. Второе строковое выражение.
  • Compare — Необязательный параметр. Указывает сравнение строк.Он может принимать следующие значения.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение (по умолчанию)
  • 1 = vbTextCompare — выполняет сравнение текста

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim var1 as Variant
   msgbox("Line 1 :" & StrComp("Microsoft","Microsoft"))
   msgbox("Line 2 :" &StrComp("Microsoft","MICROSOFT"))
   msgbox("Line 3 :" &StrComp("Microsoft","MiCrOsOfT"))
   msgbox("Line 4 :" &StrComp("Microsoft","MiCrOsOfT",1))
   msgbox("Line 5 :" &StrComp("Microsoft","MiCrOsOfT",0))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 :0
Line 2 :1
Line 3 :1
Line 4 :0
Line 5 :1

Возвращает целочисленное значение после сравнения двух указанных строк.

String

Функция String заполняет строку указанным символом для указанного количества раз.

Синтаксис

String(number,character)

Параметр Описание

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

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   msgbox("Line 1 :" & String(3,"$"))
   msgbox("Line 2 :" & String(4,"*"))
   msgbox("Line 3 :" & String(5,100))
   msgbox("Line 4 :" & String(6,"ABCDE"))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 :$$$
Line 2 :****
Line 3 :ddddd
Line 4 :AAAAAA

Возвращает строку с указанным символом для указанного количества раз.

StrReverse

Функция StrReverse меняет указанную строку.

Синтаксис

StrReverse(string)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   msgbox("Line 1 : " & StrReverse("VBSCRIPT"))
   msgbox("Line 2 : " & StrReverse("My First VBScript"))
   msgbox("Line 3 : " & StrReverse("123.45"))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1 : TPIRCSBV
Line 2 : tpircSBV tsriF yM
Line 3 : 54.321

Возвращает строку после изменения последовательности символов данной строки.

 С уважением, авторы сайта Компьютерапия

Понравилась статья? Поделитесь ею с друзьями и напишите отзыв в комментариях!

VBA String functions do not replace the string, but the result of these functions creates a new string. There are many string functions in VBA. They are all categorized under String or Text functions. Some important functions are the LEFT function to get the value from the left and the RIGHT function to get the value from the right or the MID function, LEN, and INSTR function.

String functions are so important. We can extract any characters from the string by finding the number of characters of the supplied string.

We can extract characters from the left side of the string, we can extract from the right side of the string, we can extract from the middle of the string, we can combine two texts, and we can split them at the same time as well.

It is important to have a fair bit of knowledge about all these VBA functionsVBA 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 as part of the large project.

Table of contents
  • Excel VBA String Functions
    • List of Top 6 String Functions in VBA
      • #1 – LEN Function
      • #2 – LEFT Function
      • #3 – RIGHT Function
      • #4 – MID Function
      • #5 – TRIM Function
      • #6 – Instr Function
    • Recommended Articles

List of Top 6 String Functions in VBA

  1. LEN Function
  2. LEFT Function
  3. RIGHT Function
  4. MID Function
  5. TRIM Function
  6. Instr Function

VBA String Functions

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 String Functions (wallstreetmojo.com)

One thing we would like to say is that “the VBA string functions are text functions in the worksheet.”

You must have already used LEN, LEFT, RIGHT, MID, and SUBSTITUTE excel functionsSubstitute function in excel is a very useful function which is used to replace or substitute a given text with another text in a given cell, this function is widely used when we send massive emails or messages in a bulk, instead of creating separate text for every user we use substitute function to replace the information.read more to play around with the data. In VBA, too, we can use them to play around with the data.

We will discuss some of the important functions of this article.

You can download this VBA String Functions Excel Template here – VBA String Functions Excel Template

#1 – LEN Function

LEN stands for “LENGTH.” Therefore, it will give us the number of characters involved in the supplied string. For example, if you supply the word “Hello,” LEN in the excelThe Len function returns the length of a given string. It calculates the number of characters in a given string as input. It is a text function in Excel as well as an inbuilt function that can be accessed by typing =LEN( and entering a string as input.read more function will return 5 because there are five characters in the word “Hello.”

The below code will show the example.

Code:

Sub LEN_Example()

  Dim TotalCount As String

  TotalCount = Len("Hello")

  MsgBox TotalCount

End Sub

It will show the result in the message box as 5.

VBA LEN Example

#2 – LEFT Function

We need to use the VBA LEFTExcel VBA Left is an inbuilt worksheet text function that facilitates the user to extract a certain number of characters (denoted as N) from the left side of a string. It helps in pulling the leftmost substring from a particular string in the data set.read more function to extract the characters from the left side of the string. First, take a look at the syntax of the LEFT function.

LEFT Formula

  • The string is what the string we are trying to extract is.
  • Length is nothing but how many characters you need from the left side of the supplied String.

Code:

Sub LEFT_Example()

  Dim FirstName As String

  FirstName = Left("Sachin Tendulkar", 6)

  MsgBox FirstName

End Sub

It will extract the first six characters from the string “Sachin Tendulkar.” So, the result will be the first name,  “Sachin.”

VBA LEFT Example

#3 – RIGHT Function

Like how we have extracted values from the left side of the string similarly, we can also extract from the right side of the string.

The syntax of the RIGHT functionRight function is a text function which gives the number of characters from the end from the string which is from right to left. For example, if we use this function as =RIGHT ( “ANAND”,2) this will give us ND as the result.read more is the same as the LEFT function.

Right Formula

  • The string is what the string we are trying to extract is.
  • Length is nothing but how many characters you need from the right side of the supplied String.

Code:

Sub RIGHT_Example()

  Dim LastName As String

  LastName = Right("Sachin Tendulkar", 9)

  MsgBox LastName

End Sub

It will extract 9 characters from the string “Sachin Tendulkar.” So, the result will be the last name “Tendulkar.”

VBA Right Example

#4 – MID Function

We can extract the characters from the left and right sides and the middle of the string. Below is the syntax of the VBA MID functionVBA MID function extracts the middle values from the supplied sentence or word. It is categorized under the String and Text function and is a worksheet function.read more.

MID formula

  • String to Search: From which string do we need the middle value?
  • Starting Position: What is the starting character position number to extract?
  • Number of Characters to Extract: How many characters need to be extracted from the Starting Position?

For example, if the name is “Sachin Ramesh Tendulkar,” the middle name is “Ramesh” in this string starting position of the character to be extracted 8. Therefore, we need six characters from the starting position. The below code will extract the middle value.

Code:

Sub MID_Example()

  Dim MiddleName As String

  MiddleName = Mid("Sachin Ramesh Tendulkar", 8, 6)

  MsgBox MiddleName

End Sub

It will extract “Ramesh” from the middle of the string “Sachin Ramesh Tendulkar.”

VBA String Functions Example

#5 – TRIM Function

TRIM is the function of cleaning the data. It will eliminate unwanted space characters from the string. First, take a look at the syntax of the TRIM function.

Trim formula

It is straightforward what value or string you want to trim.

For example, assume you have the string “Hello, How are you?.” Here, we have unnecessary space characters before the word “Hello,” so by using TRIM. We can eliminate this.

Code:

Sub TRIM_Example()

  Dim MyValue As String

  MyValue = Trim(" Hello How are you?")

  MsgBox MyValue

End Sub

It will delete the unwanted space characters from the supplied string.

VBA String Functions Example

We have LTRIM and RTRIM functions as well in VBA. For example, LTRIM will delete unwanted spaces from the left side of the string, and RTRIM deletes unwanted spaces from the right side.

#6 – Instr Function

The Instr function helps find the position of the supplied character in the string. The syntax of the INSTR function is as follows:

Instr Formula

  • [Start] From which position of the supplied string do we need the position?
  • [String1] What is the string you are referring to?
  • [String2] What character are you searching for in [String1]?

For example, if you have the word “Recipe” and you want to find the position of the character “e” from the first place below, the code will show the position of the letter “e.”

Code:

Sub INSTR_Example()

  Dim MyValue As String

  MyValue = InStr(1, "Recipe", "e")

  MsgBox MyValue

End Sub

So, from the first position of the string letter “e” position is 2.

VBA String Functions Example

If you want the position of the second appearance of the letter “e,” then you need to use the Start argument as 3.

Code:

Sub INSTR_Example()

  Dim MyValue As String

  MyValue = InStr(3, "Recipe", "e")

  MsgBox MyValue

End Sub

So, in this case, the position of the letter “e” after the first appearance is 6th.

VBA String Functions Example 1

These are some of the important String functions. We hope you have enjoyed it.

Recommended Articles

This article has been a guide to VBA String Functions. Here, we learn a list of the top 6 VBA String functions, including LEN, LEFT, MID, Right, Instr, and Trim, along with examples and a downloadable Excel template. Below are some useful Excel articles related to VBA: –

  • VBA Right Function
  • Excel Trim Formula
  • ROUND Formula Excel
  • Worksheet Functions in VBA

Понравилась статья? Поделить с друзьями:
  • Left right page word
  • Left margin line word
  • Left in chinese word
  • Left excel как пользоваться
  • Left align text in word