Substrings Left, Right and Mid are three Visual Basic functions to locate sections of a string. All of the following examples use the string "strExample" with the following value. strExample = "Please try to substring this" The Left function returns the requested number of characters from the left side of the string. Code: Me.Print Left(strExample, 10) Returns, "Please try" The Right function returns the requested number of characters from the right side of the string. Code: Me.Print Right(strExample, 18) Returns, "do what you can do" The Mid function returns the middle of a string. It takes three parameters, the string, the starting position and the length of the string to be returned. Code: Me.Print Mid(strExample, 8, 6) Returns, "try to" The Len function is used to determine the length of a string. The next example uses the Len and the Mid function to print a string of text down the form. Code: Dim counter As Integer Const strExample As String = "Please try to do what you can do" For counter = 1 To Len(strExample) Me.Print Mid(strExample, counter, 1) Next counter String Concatenation Strings are joined together using the & operator. Code: Dim strFirst As String, strSecond As String, strResult As String strFirst = "Too " strSecond = "bad!" strResult = strFirst & strSecond Me.Print strResult The concatenation operator is useful for building up long strings a bit at a time. Code: Dim strSQL As String strSQL = "SELECT Surname, TelNo " & _ "FROM Customer " & _ "ORDER BY Surname" Searching a String InStr and InStrRev are two Visual Basic functions to locate one string inside another. InStr locates the first occurrence of the string, and InStrRev locates the last occurrence. Code: Const strExample As String = "Please try to do what you can do" Dim pos As Integer pos = InStr(strExample, "do") If pos > 0 Then Me.Print "Found first occurrence of string at position " & pos Else Me.Print "String not found" End If Returns, "Found first occurrence of string at position 15" Code: Const strExample As String = "Please try to do what you can do" Dim pos As Integer pos = InStrRev(strExample, "do") If pos > 0 Then Me.Print "Found last occurrence of string at position " & pos Else Me.Print "String not found" End If Returns, "Found last occurrence of string at position 31"
I think that the Mid function is often used whenever you need to extract a certain string from a big string. I often do it in the programs I do. You extract only what you want and then you work with that string or display it to the user in a listbox, combo box, etc.. Luis Lazo