How to use tab in VBA


There are two ways to specify a tab character using VBA:

  • vbTab
  • chr(9)

Both of these constants represent a tab character in VBA.

The following example shows how to use each of these constants in practice.

Example: How to Specify Tab Character Using VBA

Suppose we have the following list of first and last names in Excel:

Suppose we would like to use VBA to create a message box that displays each of these first and last names with a tab between them.

We can create the following macro to do so:

Sub UseTab()
    
Dim i As Integer
Dim AllNames As String

For i = 2 To 11
AllNames = AllNames & Range("A" & i).Value & vbTab & Range("B" & i).Value & vbNewLine
Next i

MsgBox AllNames
    
End Sub

When we run this macro, we receive the following message box as output:

VBA use vbTab character

Notice that we used vbTab to concatenate the first and last names together in each row with a tab.

We then used the vbNewLine constant to add each new name to a new line in the message box.

If we’d like, we could have also use chr(9) to specify a tab character as well:

Sub UseTab()
    
Dim i As Integer
Dim AllNames As String

For i = 2 To 11
AllNames = AllNames & Range("A" & i).Value & chr(9) & Range("B" & i).Value & vbNewLine
Next i

MsgBox AllNames
    
End Sub

When we run this macro, we receive the following message box as output:

VBA use vbTab character

Notice that vbTab and chr(9) both produce the same results.

x