String Functions
CStr([expr])
Converts a variable expression to a string
Example:
Dim curDate as Date
' set our date variable to the current date/time.
curDate = Now()
' MsgBox expects a string so we need to convert our date.
MsgBox(CStr(curDate))
' Produces a message box with the current date and time.
LCase([string])
UCase([string])
Converts a string to lower case (or upper case with UCase() function.)
Example:
Dim txt as Date
txt = "This is a beautiful day!"
txt = UCase(txt)
' txt = "THIS IS A BEAUTIFUL DAY!".
txt = LCase(txt)
' txt = "this is a beautiful day!".
Left([string], [length])
Right([string], [length])
Returns a specific number of characters from the left side (right side with the Right() Function) of a string
Example:
Dim txt as Date
txt = "This is a beautiful day!"
txt = Left(txt, 6)
' txt = "This i".
txt = Right(txt, 2)
' txt = " i".
Len([string]))
Returns the number of characters in a string
Example:
Dim txt as String
Dim cnt as Integer
txt = "This is a beautiful day!"
cnt = Len(txt)
' cnt = 24
cnt = Len("This is a beautiful day!")
' cnt = 24
Mid([string], [start], [length]))
Returns a specified number of characters from a string
Example:
Dim txt as String
Dim txt2 as Integer
txt = "This is a beautiful day!"
txt2 = Mid(txt, 1, 1)
' txt2 = "T"
txt2 = Mid(txt, 3, 10)
' txt2 = "is is a be"
Trim([string])
LTrim([string])
RTrim([string])
Remove spaces from both sides of a string. (LTrim = left side only, RTrim = right side only)
Example:
Dim fname as Date
Dim txt as Date
fname = " Tim "
txt = "Hello" & fname & "and welcome"
' txt = "Hello Tim and welcome".
txt = "Hello" & Trim(fname) & "and welcome"
' txt = "HelloTimand welcome".
InStr([start], [string1], [string2], [compare])
InStrRev([start], [string1], [string2], [compare])
Returns the position of the first (or last with InStrRev) occurance of one string within another.
[compare] can have a value of 0 = vbBinaryCompare or 1 = vbTextCompare
Example:
Dim txt as String
Dim pos as Integer
txt = "This is a beautiful day!"
pos = InStr(0, txt, "beautiful")
' pos = 10.
FindReplace(sSearchString$, sFindWhat$, sReplaceWith$)
This function is not a built in function to VB however can be very useful in your VB applications. A simple search and replace function. Pass sSearchString$ ByRef.
VB provides a built-in Replace() function however, this functon works so much better.
Function Code:
Dim iPos As Integer, iStart As Integer
iStart% = 1
Do
iPos% = InStr(iStart%, sSearchString$, sFindWhat$)
'If not there, then get out
If iPos% = 0 Then Exit Do
'Combine left portion, new string, and right portion
sSearchString$ = Left(sSearchString, iPos% - 1) & sReplaceWith$ & _
Right(sSearchString$, Len(sSearchString$) - iPos% - Len(sFindWhat$) + 1)
'Calculate where to begin next search
iStart% = iPos% + Len(sReplaceWith$)
End Sub