Substrings
Use Left or Left$ to get the 3 left-most characters in a string
Section titled “Use Left or Left$ to get the 3 left-most characters in a string”Const baseString As String = "Foo Bar"
Dim leftText As StringleftText = Left$(baseString, 3)'leftText = "Foo"Use Right or Right$ to get the 3 right-most characters in a string
Section titled “Use Right or Right$ to get the 3 right-most characters in a string”Const baseString As String = "Foo Bar"Dim rightText As StringrightText = Right$(baseString, 3)'rightText = "Bar"Use Mid or Mid$ to get specific characters from within a string
Section titled “Use Mid or Mid$ to get specific characters from within a string”Const baseString As String = "Foo Bar"
'Get the string starting at character 2 and ending at character 6Dim midText As StringmidText = Mid$(baseString, 2, 5)'midText = "oo Ba"Use Trim to get a copy of the string without any leading or trailing spaces
Section titled “Use Trim to get a copy of the string without any leading or trailing spaces”'Trim the leading and trailing spaces in a stringConst paddedText As String = " Foo Bar "Dim trimmedText As StringtrimmedText = Trim$(paddedText)'trimmedText = "Foo Bar"Remarks
Section titled “Remarks”VBA has built-in functions for extracting specific parts of strings, including:
Left/Left$Right/Right$Mid/Mid$Trim/Trim$
To avoid implicit type conversion onverhead (and therefore for better performance), use the $-suffixed version of the function when a string variable is passed to the function, and/or if the result of the function is assigned to a string variable.
Passing a Null parameter value to a $-suffixed function will raise a runtime error (“invalid use of null”) - this is especially relevant for code involving a database.