When we join two strings together, this is called concatenation. According to Merriam-Webster, concatenate means to “link together in a series or chain”. This lesson covers string concatenation.
Basic Concatenation
Concatenation can use ‘+’ operator. 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
The standard operator used to join strings is the ampersand (&).
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
QuickHint:
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:
Visual Basic
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:
Visual
Basic
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
Example
str1 = "One" str2 = "Two" Print str1; Print str2
Output: OneTwo