How to specify a Tab Character in VBA in Excel

 

In this article, we have created two macros to understand the formatting of tab character within VBA.

We have taken data in the range A9:A11 as raw data.

 

ArrowRaw

 

In example 1, we have created a string in which we have consolidated data from cells within the range A9:A11, separated by tab characters (vbTab). When we display the string using a message box, we will be able to see tab spacing.

 

ArrowFirstOutput

 

However, when we insert string value in cell A14, tab spacing is not visible. We have used some Excel formulas to show tab characters exist between the words.

 

ArrowFormulas

 

In example 2, we have separated each character in the string value of cell A14 and we have used new line character (vbNewLine) to insert line breaks. Output of example 2 is also displayed using a message box.

 

ArrowSecondOutput

 

Please follow below for the code


Option Explicit

Sub example1()

'Declaring variable
Dim MainString As String

'Concatenating value from range A9 to A11 separated by Tab character
MainString = Range("A9").Value & vbTab & Range("A10").Value & vbTab & Range("A11").Value

'Display string in message box
MsgBox MainString

'Assigning value to cell A14
Range("A14").Value = MainString

End Sub

Sub example2()

'Declaring variables
Dim i, CharLength As Integer
Dim Output As String
Dim InputValue As String

'Getting input value from cell A14
InputValue = Range("A14").Value
CharLength = Len(InputValue)

'Looping through all the characters in the input value
For i = 1 To CharLength
    'Creating string in which each character in the input is separated by new line
    Output = Output & Asc(Mid(InputValue, i, 1)) & " " & Mid(InputValue, i, 1) & vbNewLine
Next i

'Displaying output using message box
MsgBox Output

End Sub

 

If you liked this blog, share it with your friends on Facebook. Also, you can follow us on Twitter and Facebook.

We would love to hear from you, do let us know how we can improve our work and make it better for you. Write to us at info@exceltip.com



Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>