Return to VBA Code Examples

VBA Mid Function – Extract Characters From Middle of String

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:

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.

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.

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.

Mid Function Extract Second Word from a Phrase

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.

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).


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!