How can I specify a tab character using VBA and what are some examples of using it?

VBA, or Visual Basic for Applications, is a programming language used in Microsoft Office applications to automate tasks and create customized solutions. In VBA, a tab character is a special character used to create horizontal spacing in text or data. To specify a tab character in VBA, the “vbTab” constant can be used. For example, “MsgBox “Name” & vbTab & “Age” will display “Name” followed by a tab character and then “Age” in a message box. Other examples of using tab characters in VBA include formatting data in a spreadsheet, creating tables in a Word document, or separating columns in a text file. Using tab characters in VBA can improve the readability and organization of data, making it a useful tool for creating efficient and professional-looking solutions.

Specify a Tab Character Using VBA (With Examples)


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 StringFor 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 StringFor 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.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

x