Vba excel функция mid

Извлечение (вырезание) части строки с помощью кода 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

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

In this Article

  • Mid Function
    • Mid Function Get n Characters
    • Mid Function Get n Characters in a Variable
    • Mid Function Get n Characters from a Cell
    • Mid Function Replace n Characters
    • Mid Function Extract Second Word from a Phrase

This tutorial will demonstrate how to use the Mid VBA function to extract characters from the middle of a text string.

Mid Function

Mid Function Get n Characters

The VBA Mid function returns n characters from a string starting from position m:

Sub MidExample_1()
MsgBox Mid("ABCDEFGHI", 4, 1)   'Result is: "D"
MsgBox Mid("ABCDEFGHI", 4, 2)   'Result is: "DE"
MsgBox Mid("ABCDEFGHI", 4, 50) 	'Result is: "DEFGHI"

MsgBox Mid("ABCDEFG hI", 6, 1)  'Result is: "F"
MsgBox Mid("ABCDEFG hI", 6, 2)  'Result is: "FG"
MsgBox Mid("ABCDEFG hI", 6, 4) 	'Result is: "FG h"
End Sub

Mid Function Get n Characters in a Variable

As shown above, you can define a string simply by entering text surrounded by quotation marks. But the MID Function will also work with string variables. These examples will extract n characters from a string starting from position m.

Sub MidExample_2()
Dim StrEx As String 'Define a string variable

StrEx = "ABCDEFGHI"
MsgBox Mid(StrEx, 2, 1)		'Result is: "B"
MsgBox Mid(StrEx, 2, 2)       	'Result is: "BC"
MsgBox Mid(StrEx, 2, 50) 	'Result is: "BCDEFGHI"
End Sub

Mid Function Get n Characters from a Cell

Strings can be defined in VBA code but also you can use values from cells. Read the value of a cell, keep it in a string variable, and extract n characters from that Worksheet Cell value starting from position m.

Sub MidExample_3()
Dim StrEx As String 'Define a string variable

'Read the value of cell A1 in worksheet Sheet1
StrEx = ThisWorkbook.Worksheets("Sheet1").Range("A1").Value
'For this example the value of cell A1 is "May the Force be with you"

MsgBox Mid(StrEx, 4, 6) 'Result is: " the F" (Note the space at the start)
MsgBox Mid(StrEx, 2, 8) 'Result is: "ay the F"
MsgBox Mid(StrEx, 3, 4) 'Result is: "y th"
End Sub

Mid Function Replace n Characters

In the examples above, Mid function did not change the original string. It returned a part of it, leaving the original string intact. Mid Function can be used to replace characters in a string.

Sub MidExample_4()
Dim StrEx As String 'Define a string variable

Sub MidExample_4()
Dim StrEx As String 'Define a string variable

StrEx = "May the Force be with you"
Mid(StrEx, 5, 1) = "VWXYZ"
MsgBox StrEx 'Result is: "May Vhe Horce be with you"
'Mid Function found position 5 and replaced 1 character in the original string

StrEx = "May the Force be with you"
Mid(StrEx, 5, 3) = "VWXYZ"
MsgBox StrEx 'Result is: "May VWX Horce be with you"
'Mid Function found position 5 and replaced 3 characters in the original string

StrEx = "May the Force be with you"
Mid(StrEx, 5, 8) = "VWXYZ"
MsgBox StrEx 'Result is: "May VWXYZorce be with you"
'Mid Function found position 5 and tried to replaced 8 characters. 
'"VWXYZ" has only 5 characters, so only 5 characters were replaced.
End Sub

We can use VBA Mid function with VBA Instr function to get the second word in a text.

VBA InStr function can return the position of a character inside the text.

InStr("Two words", " ") 'Result is 4

We can use InStr to find the first space, then we can use again InStr starting the search after the first space to find the second space in the text. Finally, we can use Mid function to extract the word because we know the starting position of the second word and its length (the difference between the two spaces positions).

Sub MidExample_5()
Dim StrEx As String 'Define a string variable
Dim StartPos As Integer
Dim EndPos As Integer
Dim SecondWord As String
StrEx = "James Earl Jones is an Actor"

StartPos = InStr(StrEx, " ")
'Result is 6
'Find the position of the first space

EndPos = InStr(StartPos + 1, StrEx, " ")
'Result is 11
'Find the position of the second space by starting search after the first space


SecondWord = Mid(StrEx, StartPos + 1, EndPos - StartPos - 1)
'Mid extracts the characters starting after the first space (StartPos +1)
'Mid uses also the length of the second word.
'That is the difference between spaces positions -1

MsgBox SecondWord
'Result is Earl

End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

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

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Mid function (Visual Basic for Applications)

vblr6.chm1011070

vblr6.chm1011070

office

5d5e7712-459a-d504-dae6-4b52a9a90c6f

03/19/2019

high

Returns a Variant (String) containing a specified number of characters from a string.

Syntax

Mid(string, start, [ length ])

The Mid function syntax has these named arguments:

Part Description
string Required. String expression from which characters are returned. If string contains Null, Null is returned.
start Required; Long. Character position in string at which the part to be taken begins. If start is greater than the number of characters in string, Mid returns a zero-length string («»).
length Optional; Variant (Long). Number of characters to return. If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.

Remarks

To determine the number of characters in string, use the Len function.

[!NOTE]
Use the MidB function with byte data contained in a string, as in double-byte character set languages. Instead of specifying the number of characters, the arguments specify numbers of bytes. For sample code that uses MidB, see the second example in the example topic.

Example

The first example uses the Mid function to return a specified number of characters from a string.

Dim MyString, FirstWord, LastWord, MidWords
MyString = "Mid Function Demo"    ' Create text string.
FirstWord = Mid(MyString, 1, 3)    ' Returns "Mid".
LastWord = Mid(MyString, 14, 4)    ' Returns "Demo".
MidWords = Mid(MyString, 5)    ' Returns "Function Demo".

The second example use MidB and a user-defined function (MidMbcs) to also return characters from string. The difference here is that the input string is ANSI and the length is in bytes.

Function MidMbcs(ByVal str as String, start, length)
    MidMbcs = StrConv(MidB(StrConv(str, vbFromUnicode), start, length), vbUnicode)
End Function

Dim MyString
MyString = "AbCdEfG"
' Where "A", "C", "E", and "G" are DBCS and "b", "d", 
' and "f" are SBCS.
MyNewString = Mid(MyString, 3, 4)
' Returns "CdEf"
MyNewString = MidB(MyString, 3, 4)
' Returns "bC"
MyNewString = MidMbcs(MyString, 3, 4)
' Returns "bCd"

See also

  • Functions (Visual Basic for Applications)

[!includeSupport and feedback]

VBA Mid function in Excel is categorized as a Text/String function in VBA. It is a built-in function in MS Office Excel. It returns a specified number of characters from a specified/given string. It has two mandatory parameters and one optional parameter. If input string contains Null, then the function returns Null.

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

Table of Contents:

  • Overview
  • Syntax of VBA Mid Function
  • Parameters or Arguments
  • Where we can apply or use the VBA Mid Function?
  • Example 1: Extract a sub-string from the specified string
  • Example 2: Get First_Name from Full_Name
  • Example 3: Extract Email Id from Email
  • Example 4: Extract File Extension from the File Name
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the VBA Mid function is

Mid(String, Start, [Length])

Note: This Mid function returns a specified number of characters from a supplied string.

Parameters or Arguments

This function has two mandatory parameters and one optional argument for the Mid Function.
Where
String:The string is a mandatory argument. It represents a string which we want to extract a sub-string from
Start:The start is a mandatory argument. It represents a starting position of substring.If start value is greater than the number of characters in string, the Mid function returns an empty string.
Length:The length is an optional parameter. It represents a number of characters to be extracted from a string.

Where we can apply or use the VBA Mid Function?

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

Example 1: Extract a substring from the specified string

Here is a simple example of the VBA Mid function. This below example macro returns a substring. The output of the below macro is ‘Welcome’.

'Extract a substring from the specified string
Sub VBA_Mid_Function_Ex1()
    
    'Variable declaration
    Dim sInput As String
    Dim sOutput As String
    
    sInput = "Welcome to VBAF1"
    
    sOutput = Mid(sInput, 12, 5)
       
    MsgBox " The substring is : " & sOutput, vbInformation, "VBA Mid Function"
    
End Sub

Output: Here is the screen shot of the first example output.
VBA MID Function

Example 2: Get First_Name from Full_Name

Here is a simple example of the VBA Mid function. This below example macro returns a substring. The output of the below macro is ‘Adam’.

'Get First_Name from Full_Name
Sub VBA_Mid_Function_Ex2()

    'Variable declaration
    Dim sInput As String
    Dim sTemp() As String
    Dim sOutput As String
    
    sInput = "Adam Christ John"
    
    sTemp = Split(sInput, " ")
    
    sOutput = Mid(sInput, 1, Len(sTemp(0)))
       
    MsgBox " The First Name is : " & sOutput, vbInformation, "VBA Mid Function"

End Sub

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

Example 3: Extract Email Id from Email

Here is a simple example of the VBA Mid function. This below example macro returns a substring. The output of the below macro is ‘vbahelp.contact’.

'Extract Email Id from Email
Sub VBA_Mid_Function_Ex3()

    'Variable declaration
    Dim sInput As String
    Dim sTemp() As String
    Dim sOutput As String
    
    sInput = "vbahelp.contact@gmail.com"
    
    sTemp = Split(sInput, "@")
    
    sOutput = Mid(sInput, 1, Len(sTemp(0)))
       
    MsgBox " The Email Id is : " & sOutput, vbInformation, "VBA Mid Function"
    
End Sub

Output: Here is the screen shot of the third example output.
VBA MID Function

Example 4: Extract File Extension from the File Name

Here is a simple example of the VBA Mid function. This below example macro returns a substring. The output of the below macro is ‘xls’.

'Extract File Extension from the File Name
Sub VBA_Mid_Function_Ex4()

   'Variable declaration
    Dim sInput As String
    Dim sTemp() As String
    Dim sOutput As String
    
    sInput = "C:/Test/File_Name.xls"
    
    sTemp = Split(sInput, ".")
    
    sOutput = Mid(sInput, Len(sTemp(0)) + 2, Len(sTemp(1)))
       
    MsgBox " The File extension is : " & sOutput, vbInformation, "VBA Mid Function"
    
End Sub

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

Instructions to Run VBA Macro Code or Procedure:

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

Instructions to run VBA Macro Code

Other Useful Resources:

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

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Like this post? Please share to your friends:
  • Vba excel это впр
  • Vba excel функция len
  • Vba excel функция cells
  • Vba excel эта книга workbook
  • Vba excel эта закладка