The Mid statement in VBA (Visual Basic for Applications) is used to replace a specified number of characters in a string with characters from another string. It’s particularly useful for modifying only a part of a string, without affecting the rest of it.
Here’s how you can use the Mid statement:
Syntax
VBA
Mid(stringVar, startPosition, [length]) = replacementString
- stringVar: This is the string variable whose contents you want to modify. It must be a variable, not a literal string or a string returned by a function.
- startPosition: The position in stringVar where the replacement starts. The first character in the string is at position 1.
- length (optional): The number of characters to replace. If omitted, the replacement continues to the end of stringVar.
- replacementString: The string that will replace characters in stringVar.
Example 1: Basic Usage
VBA
In this example, the Mid statement replaces the characters starting from the 7th position (“World”) in myString with “VBA”. Since the length parameter is not provided, it replaces until the end of the string.
Dim myString As String
myString = "Hello World"
Mid(myString, 7, 5) = "VBA"
' myString now contains "Hello VBA"
Example 2: Specifying Length
VBA
Here, only the first 3 characters starting from the 7th position (“Wor”) are replaced with “VBA”, leaving the remaining characters (“ld”) unchanged.
Dim myString As String
myString = "Hello World"
Mid(myString, 7, 3) = "VBA"
' myString now contains "Hello VBAld"
Important Points to Remember:
- Variable Requirement: The string to be modified must be a variable. You cannot use the Mid statement directly on a string literal or a function’s return value.
- String Length Alteration: The Mid statement doesn’t alter the total length of the string. It only replaces characters within the existing length.
- Error Handling: If startPosition is less than 1 or beyond the length of stringVar, the Mid statement doesn’t modify the string and doesn’t raise an error. Similarly, if length is specified as a negative number, the string remains unchanged.