The String Data Type

A variable that will always contain a string and never a numeric value can be declared with the String data type.


Private dataName As String

Before you assign data, a string variable contains an empty string (""). You can then assign strings to this variable and manipulate it using string functions. You use string literals in Visual Basic by enclosing the string within double quotation marks.


dataName = "Database"
dataName = Left(dataName, 4)

By default, a string variable or argument is a variable-length string; the string grows or shrinks as you assign new data to it. You can also declare strings that have a fixed length. You specify a fixed-length string with the following syntax.

String * size

For example, to declare a string that's always 50 characters long, use code such as the following:


Dim empName As String * 50

If you assign a string of fewer than 50 characters, empName is padded with enough trailing spaces to total 50 characters (before any assignment, the variable contains 50 spaces). If you assign a string that's too long for the fixed-length string, Visual Basic truncates the characters, as in the following example.


Dim tempString As String * 4, dataName As String

dataName = "Database"
tempString = dataName
MsgBox tempString & " : " & dataName

The preceding code produces the following output.


Database : Data

Because fixed-length strings are padded with trailing spaces, you may find the Trim, LTrim, and RTrim functions useful when working with fixed-length strings. For more information, see "Trim," "LTrim," or "RTrim" in Help.