String Concatenation


Visual Basic 6 provides you few ways to concatenate strings. This lesson teaches you the ways to concatenate two or more strings in VB6.

The joining of two or more strings is called string concatenation.


Concatenation using '+' operetor

You can join multiple strings using the "+" operator.

Example:
Private Sub cmdJoin_Click()
    Dim str As String, str1 As String, str2 As String
    str1 = "Visual"
    str2 = "Basic"
    str = str1 + str2
    Print str
End Sub

Output: visualbasic


Concatenation using '&' operator

The best and standard way to concatenate is to use the "&" operator.

Example:
Private Sub cmdConcat_Click()
    Dim str As String, str1 As String, str2 As String
    str1 = "New"
    str2 = "Program"
    str = str1 & str2
    Print str
End Sub

Output: NewProgram


Important Note: Sometimes, the '&' operator is a better choice for concatenation. If you join a string with a numeric value, the '+' operator will show a Type Mismatch run-time error while the "&" operator will do the job without throwing an error. See the below example.Example :

Dim n As Integer, s As String
n = 34
s = "one"

MsgBox n & s   'if you use +, it will show an error



The vbTab constant

vbTab is the constant for Tab character.

Example:

Private Sub Command1_Click()
    Dim s1 As String, s2 As String, str As String
    s1 = "Visual"
    s2 = "Basic"

    MsgBox s1 & vbTab & s2
End Sub

Output:

program example using the vbTab constant




The vbCrLf constant

vbCrLf is the constant for Carriage-return/Line feed character.

Example:

Dim s1 As String, s2 As String, str As String
s1 = "Visual"
s2 = "Basic"

MsgBox s1 & vbCrLf & s2

Output: 

program using vbCrLf constant


Using the semicolon ';' operator

Semicolon in a Print statement suppresses the line feed. That is why when you print two consecutive strings using ';' operator in between, you see two strings together. But this operator does NOT concatenate strings.

Example:
Dim str As String, str1 As String, str2 As String
str1 = "One"
str2 = "Two"
Print str1; str2

Output: OneTwo


str1 = "One"
str2 = "Two"
Print str1; 

Print str2

Output: OneTwo