String Functions

Getting text

To get all the text from a string you use the following syntax:

VariableOrProperty = String

For example, the following code sets Form1 caption property to the string contained in String1

' Declare the variable
Dim sString As String
' Fill the variable
sString = "Hello World"
' Assign String1 to Form1's Caption
Form1.Caption = sString

However, sometimes you will find you only want to get part of a string. The most basic functions are Left, Right and Mid. Left gets a specified number of letters from the left side of a string. Left uses the following syntax:

Left$(String, Length)

The following code will display a message box with 'Hel'. It has taken three letters from the left side of String1

' Declare the variable
Dim sString As String
' Fill the variable
sString = "Hello"
' Get the first three characters from String1
MsgBox Left$(sString, 3)

Right uses the same syntax except returns the specified number of letters from the right side of a string. The following code will display a message box with 'llo'. It has taken three letters from the right side of String1

' Declare the variable
Dim sString As String
' Fill the variable
sString = "Hello"
' Get the first three characters from String1
MsgBox Right$(sString, 3)

Mid gets a specified number of letters from a specified point in a string (counted from the left). Mid uses the following syntax:

Mid$(String, Start, Length)

The following code will display a message box with 'll'. It has taken two letters from the third character onwards from String1

' Declare the variable
Dim String1 As String
' Fill the variable
String1 = "Hello"
' Get two characters from pos 3 onwards in String1
MsgBox Mid$(String1, 3, 2)

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“My definition of an expert in any field is a person who knows enough about what's really going on to be scared.” - P. J. Plauger