String Data Type

A string is a sequence of characters. (An empty string has no characters, however.) A string may contain ordinary text characters (letters, digits, and punctuation) as well as special control characters such as vbCrLf (carriage return/line feed characters) or vbTab (tab character). As we have seen, a string constant is enclosed within quotation marks. The empty string is denoted by a pair of adjacent quotation marks, as in:

EmptyString = ""

There are two types of string variables in VBA: fixed-length and variable-length. A fixed-length string variable is declared as follows:

Dim FixedStringVarName As String * StringLen

For instance, the following statement declares a fixed-length string of length 10 characters:

Dim sName As String * 10

Observe that the following code, which concatenates two strings:

Dim s As String * 10 s = "test" Debug.Print s & "/"

and produces the output:

This shows that the content of a fixed-length string is padded with spaces in order to reach the correct length.

A variable-length string variable is a variable that can hold strings of varying lengths (at different times, of course). Variable-length string variables are declared simply as:

Dim VariableStringVarName As String As an example, the code:

Dim s As String s = "test" Debug.Print s & "/" s = "another test" Debug.Print s & "/"

produces the output:


another test/

Variable-length string variables are used much more often than fixed-length strings, although the latter have some very specific and important uses (which we will not go into in this book).

0 0

Post a comment