The Right function in VBA extracts a specified number of characters from the right side of a given string.
Syntax:
Right(string, length)
Parameter:
string: The string from which you want to extract the rightmost characters.
length: The number of characters to extract from the right side of the string.
Return Value:
String: Returns the extracted substring from the right side of the original string.
Example: Extract the last 3 characters
Dim str1 As String
Dim rightStr As String
str1 = "Hello, World!"
rightStr = Right(str1, 3)
' rightStr will be "d!"
Extract more characters than the string length:
Dim str1 As String
Dim rightStr As String
str1 = "Hello, World!"
rightStr = Right(str1, 15)
' rightStr will be "Hello, World!" (Returns the entire string)
Use Cases:
String Manipulation:
Extracting file extensions from filenames (e.g., “.txt”, “.doc”).
Extracting the last few digits of a number.
Extracting specific parts of a string based on their position from the right.
Data Extraction:
Extracting specific information from text strings.
Key Considerations:
If length is 0, an empty string (“”) is returned.
If length is greater than the length of the string, the entire string is returned.