center text in a fixed string space

User avatar
sal21
PlatinumLounger
Posts: 4353
Joined: 26 Apr 2010, 17:36

center text in a fixed string space

Post by sal21 »

i have a free space of 60 charachter.
now i need to center a text in this string...

note:
the text to center Have a variable lenght, but max 60 charachter

User avatar
HansV
Administrator
Posts: 78448
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: center text in a fixed string space

Post by HansV »

If you use a fixed-width font such as Courier New or Consolas, you can use:

Code: Select all

    Dim strShort As String
    Dim strLong As String
    Dim lngSpace As Long
    strShort = "Salvatore"
    lngSpace = (60 - Len(strShort) \ 2
    strLong = Space(lngSpace) & strShort & Space(60 - lngSpace)
Best wishes,
Hans

User avatar
sal21
PlatinumLounger
Posts: 4353
Joined: 26 Apr 2010, 17:36

Re: center text in a fixed string space

Post by sal21 »

HansV wrote:
20 Oct 2021, 07:19
If you use a fixed-width font such as Courier New or Consolas, you can use:

Code: Select all

    Dim strShort As String
    Dim strLong As String
    Dim lngSpace As Long
    strShort = "Salvatore"
    lngSpace = (60 - Len(strShort) \ 2
    strLong = Space(lngSpace) & strShort & Space(60 - lngSpace)
WORK!
Now i use Consolas, for tabular text in my project!

mirfield
Lounger
Posts: 27
Joined: 04 Jun 2013, 08:32
Location: North Yorkshire, UK

Re: center text in a fixed string space

Post by mirfield »

HansV wrote:
20 Oct 2021, 07:19
If you use a fixed-width font such as Courier New or Consolas, you can use:

Code: Select all

    strLong = Space(lngSpace) & strShort & Space(60 - lngSpace)
Wouldn't this add 25 spaces before and 35 after? You need to deduct the length of the string too

Code: Select all

    strLong = Space(lngSpace) & strShort & Space(60 - lngSpace - Len(strShort))
or just trim to the right length

Code: Select all

    strLong = Left(Space(lngSpace) & strShort & Space(60), 60)

User avatar
HansV
Administrator
Posts: 78448
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: center text in a fixed string space

Post by HansV »

Aargh - yes!

I like the last one!
Best wishes,
Hans

User avatar
Doc.AElstein
BronzeLounger
Posts: 1499
Joined: 28 Feb 2015, 13:11
Location: Hof, Bayern, Germany

Re: center text in a fixed string space

Post by Doc.AElstein »

Hello
I expect VB is wanted here, not VBA?
No matter, here’s one that often seems to get forgotten sometimes, using the Mid Statement

Code: Select all

 Let strLong = Space(60)
 Mid(strLong, lngSpace, Len(strShort)) = strShort
Alan

( the VBA equivalent of that would be, I think

Code: Select all

Let strLong = Application.WorksheetFunction.Replace(Space(60), lngSpace, Len(strShort), strShort)
)
I am having difficulty logging in with this account just now.
You can find me at DocAElstein also