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.
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.
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.
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.
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
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 firstname.lastname@example.org