Hi,
How can a string without spaces be formatted to display the string in
groups
of five characters.
Example:
246 81357 99876 54321
Only the left-most group can contain less than 5 characters
You cannot accomplish this with formatting. The best you can do, while
leaving
the original string unchanged, is to display it in the desired fashion in
another cell.
Here is a UDF (user-defined-function) that will take a string as input,
remove
any existing spaces, and then output a string spaced according to your
rules.
The default spacing is five characters, but optional arguments allow you
to
specify any desired number of characters, and also to specify whether the
formatted string fills from the right (the default) or from the left (so
that
the right-most group could contain less than L characters).
To enter this User Defined Function (UDF), <alt-F11> opens the Visual
Basic
Editor.
Ensure your project is highlighted in the Project Explorer window.
Then, from the top menu, select Insert/Module and
paste the code below into the window that opens.
To use this User Defined Function (UDF), enter a formula like
=InsertSpaces(A1)
in some cell.
=================================================
Option Explicit
Function InsertSpaces(sStr, Optional Length As Long = 5, _
Optional RightToLeft As Boolean = True)
Dim sFormat As String
Dim sTemp As String
sTemp = Replace(sStr, " ", "")
With Application.WorksheetFunction
sFormat = " " & .Rept("@", Length)
sFormat = .Rept(sFormat, .Ceiling(Len(sTemp) / Length, 1))
End With
If RightToLeft = False Then
sFormat = "!" & sFormat
End If
InsertSpaces = Trim(Format(sTemp, sFormat))
End Function
========================================
If you want to use the optional arguments, you could do that by entering a
formula of the type:
=InsertSpaces(A1,[num_spaces],[fill_direction])
for [fill_direction] -- FALSE will fill left-to-right.
--ron