How to insert / add space after every x characters in cells?
If you have multiple text strings in a list of worksheet, now, you want to insert space after every 3 or x characters in cells as following screenshot shown. How could you solve this problem in Excel quickly and easily?
Applying the following VBA code, you can quickly insert the space after every n characters for multiple cells at once, please do as follows:
1. Hold down the ALT + F11 keys to open the Microsoft Visual Basic for Applications window.
2. Then click Insert > Module, and paste the following code in the Module window.
VBA code: Insert space after every x characters:
Sub addspace() 'updateby Extendoffice 20151207 Dim i As Long Dim xCell As Range Dim xRg As Range Dim xTxt As String Dim xStr As String Dim xUpdate As Boolean On Error Resume Next xTxt = ActiveWindow.RangeSelection.Address Set xRg = Application.InputBox("Please select the data range:", "Kutools for Excel", xTxt, , , , , 8) Set xRg = Application.Intersect(xRg, xRg.Worksheet.UsedRange) If xRg Is Nothing Then Exit Sub xUpdate = Application.ScreenUpdating Application.ScreenUpdating = False For Each xCell In xRg xStr = xCell.Text xTxt = "" For i = 1 To Len(xStr) Step 4 If xTxt = "" Then xTxt = Mid(xStr, i, 4) Else xTxt = Trim(xTxt) & " " & Mid(xStr, i, 4) End If Next xCell = xTxt Next Application.ScreenUpdating = xUpdate End Sub
3. Then press F5 key to run this code, and in the prompt box, please select the cells that you want to insert space to, see screenshot:
4. And then click OK button, and the spaces have been inserted into the cell contents after every four characters, see screenshots:
Note: In the above code, you can change the number 4 to other number to insert space after. And also you can change the delimiter space to another delimiters in this rule xTxt = Trim(xTxt) & " " & Mid(xStr, i, 4) of the above code.
Kutools for Excel’s Add Text feature also can help you to solve this problem quickly and easily.
|Kutools for Excel : with more than 300 handy Excel add-ins, free to try with no limitation in 60 days.|
After installing Kutools for Excel, please do as follows:( Free Download Kutools for Excel Now! )
1. Select the text strings that you want to insert space.
2. Then click Kutools > Text > Add Text, see screenshot:
3. In the Add Text dialog box, press the space bar once into the Text box, and select the Specify option under the Position, then type the positions that you want to insert the space, see screenshot:
4. And then click Ok or Apply button, you will get the result that the spaces have been inserted after every four characters as you need.
Tips: The number of positions in Specify textbox should be separated by commas.