Search
Close this search box.

VBA – Mid String


The Mid function in VBA extracts a specific portion (substring) from a given string.

Syntax:

Mid(string, start, [length])

Parameter:

  • string: The original string from which you want to extract a substring.
  • start: The starting position within the string where the substring begins.
  • length: (Optional) The number of characters to extract from the starting position. If omitted, it extracts all characters from the starting position to the end of the string.

Return Value:

  • String: Returns the extracted substring.

Extract a specific number of characters

				
					Dim str1 As String
Dim subStr As String

str1 = "Hello, World!"
subStr = Mid(str1, 7, 5) 

' subStr will be "World"
				
			

Extract characters from a specific position to the end

				
					Dim str1 As String
Dim subStr As String

str1 = "Hello, World!"
subStr = Mid(str1, 7) 

' subStr will be "World!"
				
			

Use Cases:

  • String Manipulation:
    • Extracting specific parts of a string (e.g., filenames, usernames, domain names).
    • Parsing data from delimited strings (e.g., comma-separated values).
  • Data Extraction:
    • Extracting specific information from text files or databases.

Key Considerations:

  • If start is less than 1, an error occurs.
  • If start is greater than the length of the string, an empty string is returned.
  • If length is omitted, the function extracts all characters from the start position to the end of the string.