Contents
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
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
Dim myString As String
myString = "Hello World"
Mid(myString, 7, 5) = "VBA"
' myString now contains "Hello 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.
Example 2: Specifying Length
Dim myString As String
myString = "Hello World"
Mid(myString, 7, 3) = "VBA"
' myString now contains "Hello VBAld"
Here, only the first 3 characters starting from the 7th position (“Wor”) are replaced with “VBA”, leaving the remaining characters (“ld”) unchanged.
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.
The Mid statement is a powerful tool for string manipulation in VBA, allowing precise control over the modification of string content.